Disclaimer! This introduction to C will not make you a computer scientist! ;^0 However, after this overview you should be able to read and understand.

Slides:



Advertisements
Similar presentations
Decisions If statements in C.
Advertisements

On the first day of winter, my true love gave to me: a___________ in a tree.
The 12 Days of Christmas On the first day of Christmas my true love gave to me
Whiteboardmaths.com © 2004 All rights reserved
Structure of a C program
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
VB .NET Programming Fundamentals
An Introduction to C Programming Geb Thomas. Learning Objectives Learn how to write and compile a C program Learn what C libraries are Understand the.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
CPS120: Introduction to Computer Science
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
The Twelve Days of Christmas The twelve days of Christmas are the days between the birthday of Jesus (December 25) to Epiphany, when the baby Jesus was.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (for) Outline 4.1Introduction 4.2The.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Introduction to Programming
Twelve Days of Christmas Mathematically Speaking.
Binomial and Geometric Distributions
12 Days of Christmas. On the first day of Christmas my true love gave to me…. A partridge in a pear tree.
12 Days of Christmas PowerPoint by Meredith Inserra.
Hello, students! Today is Monday, December 13, 2010!
12 Days of Christmas On the first day of Christmas, my true love gave to me, A partridge in a pear tree. 一只站在梨树上的鹧鸪鸟 On the second day of Christmas, my.
A NOTE TO TEACHERS: The 12 Days of Christmas is a fascinating Christmas song to cover in class as there are so many ways to investigate it… What does it.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 2. Program Construction in Java. 01 Java basics.
The Twelve Days of Christmas. On the 1 st day of Christmas, my true love sent to me… …a partridge in a pear tree.
On the first day of Christmas my true love sent to me: one partridge in a pear tree.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
The Twelve Days of Christmas A song rich with symbolism.
Basic concepts of C++ Presented by Prof. Satyajit De
Chapter 4 – C Program Control
The Machine Model Memory
Computer Science 210 Computer Organization
Chapter 1.2 Introduction to C++ Programming
Lecture 7: Repeating a Known Number of Times
Data types and variables
BY GAWARE S.R. COMPUTER SCI. DEPARTMENT
C Short Overview Lembit Jürimägi.
C Basics.
Introduction to C Programming Language
Chapter 3: Understanding C# Language Fundamentals
Arrays, For loop While loop Do while loop
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Structured Program
Chapter 4 - Program Control
Introduction to C Programming
Chapter 3 - Structured Program Development
THE TWELVE DAYS OF CHRISTMAS
3 Control Statements:.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 3 - Structured Program Development
Structured Program Development in C
1. Opening.
C Programming Getting started Variables Basic C operators Conditionals
12 Days of Christmas.
CMPE212 – Reminders The other four assignments are now posted.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Introduction to C Topics Compilation Using the gcc Compiler
In this class, we will cover:
C++ Programming Basics
An Overview of C.
Variables in C Topics Naming Variables Declaring Variables
THE TWELVE DAYS OF CHRISTMAS
Twelve Days of Christmas
Puzzle A Puzzle B.
Presentation transcript:

Introduction to C Programming K Broerman Mentor, Team 868 TechHounds December, 2005

Disclaimer! This introduction to C will not make you a computer scientist! ;^0 However, after this overview you should be able to read and understand some of the default FRC code. :^)

Some Wisdom (no extra charge!) "Computer science is no more about computers than astronomy is about telescopes." E. W. Dijkstra

A Very Simple C Program /* This program will print out the message This is a C program */ #include <stdio.h> /* find and use the stdio header file */ main() { printf ("This is a C program\n“); /* \n means add a newline (linefeed) */ }

Some C Program Syntax (Nuts & Bolts) Language Component Examples pre-processor statements #include <stdio.h> #define PI 3.14159 keywords if, then, return, switch,… built-in functions +,-,*,/,!,&,|,&&,^, … variable definitions int motor_speed; function definitions float square_root(float x); executable statements motor_speed = 100; conditional statements if (motor_speed > 100) { … } ANSI library functions printf, memcpy, malloc, … comments /* clip motor speed to prevent over-current condition */

C Pre-Processor If first column contains #, indicates pre-processor command… Examples: #include <stdio.h> /* find and use stdio.h */ #define PI 3.14159 /* this is a MACRO defn */ #if 0 /* conditional compile switch */ //compiler will skip this code #else //compiler will compile this code #endif

C Comments 2 forms: /* this is a multi-line comment: */ /* now is the time for all good men to come to the aid of their country */ // this is a one-line C++ style comment: // you need double slashes on each line // for multi-line comments // like this

C Syntax Rules (partial list) Every executable statement must end with a semicolon ‘White space’ (tabs, etc) is ignored by compiler Keywords are reserved this will generate a compiler error: int switch; /* front panel switch */ C is case-sensitive!

C Variable Types Variable names are arbitrary (with some compiler-defined maximum length, typically 32 characters). C provides the following standard variable types: int  integer variable unsigned int  integer variable short  short integer long  long integer float  single precision real (floating point) variable char  character variable unsigned char  character variable

Integer Data Type Sizes and Limits (MPLAB C18) Data Type Size (bits) Minimum Value Maximum Value char 8 -128 127 unsigned char 8 0 255 int 16 -32768 32767 unsigned int 16 0 65535 short 16 -32768 32767 unsigned short 16 0 65535 short long 24 -8,388,608 8,388,607 unsigned short long 24 0 16,777,215 long 32 -2,147,483,648 2,147,483,647 unsigned long 32 0 4,294,967,295

Fun with Math You must consider storage size and usage when selecting variable types! unsigned char counter = 100; // uchar ranges from 0.. 255 counter = counter + 150; // counter now equals 250 counter = counter + 50; // counter now equals 44! int distance = 32767; // int ranges from -32768.. 32767 distance = distance + 1; // distance now equals -32768!

Floating Point Data Type Sizes and Limits (MPLAB C18) Type Size (bits) Minimum Value Maximum Value float 32 1.17549435e - 38 6.80564693e + 38 double data type  same as float on C18 compiler

So Why Not Use Floats for Everything? Floating point arithmetic is ~100x slower than integer arithmetic! (no FPU on PIC 18F8520 uC) Your FRC code will not run once the total code execution time exceeds the FRC main loop timer (26 mS)! FRC controller contains ‘only’ 2 kB of data RAM

Array Variables Arrays are defined using square brackets [ ] as follows: #define NUM_EMPLOYEES 10 #define MAX_NAME_LENGTH 256 int employee_id[NUM_EMPLOYEES]; int employee_salary[NUM_EMPLOYEES]; char employee_name[NUM_EMPLOYEES][MAX_NAME_LENGTH]; //2-D array memcpy (employee_name[2], "Ronald McDonald", 15); employee_id[2] = 10023; employee_salary[2] = 85000; /* ooops! */

Conditionals Conditionals are used within the if and while constructs: if (conditional_1) { ...block of statements executed if conditional_1 is true... } else if (conditional_2) ...block of statements executed if conditional_2 is true... else ...block of statements executed otherwise...

Conditionals Conditionals are logical operations involving comparison of quantities (of the same type) using the conditional operators: < less than <= less than or equal to == equal to != not equal to >= greater than or equal to > greater than

Boolean (True/False) Operators There are 3 boolean operators: && logical AND || logical OR ! logical NOT (inversion) Example usage: fun_weekend = !homework && !chores; in_trouble = broke_window || spilled_milk; good_student = (homework_done && !daydreaming) || have_apple;

Functions Functions allow large programs to be partitioned into smaller blocks, each of which is easier to write, read, and maintain. A function has the following layout: return-type function-name ( argument-list-if-necessary ) { ...local-declarations... ...statements … return return-value; }

Symbolic Constants // You can define constants of any type by using the #define // compiler directive. #define SPEED_MIN -100 // max reverse speed is -127 #define SPEED_MAX 100 // max forward speed is +127 int rate_limit( int requested_speed ) { if (requested_speed < SPEED_MIN) requested_speed = SPEED_MIN; else if (requested_speed > SPEED_MAX) requested_speed = SPEED_MAX; return requested_speed; }

Loops Most real programs contain some construct that loops within the program, performing repetitive actions on a stream of data or a region of memory. There are several ways to loop in C. Two of the most common are the while loop and the for loop: while (expression-is-true) { ...block of statements to execute... } for (expression_1; expression_2; expression_3)

Looping: while The while loop repeats a statement until the test at the top proves false. count = 0; while(count < 7) { // do something useful count = count + 1; }

Looping: while The while loop can also be used for waiting: while( !rc_dig_in01 ) //limit switch 1 closed? { /* energize motor! */ }

Looping: for The for loop can execute a block of code N times: for (i=0; i < FILTER_SIZE-1; i++) { filter_value[i] = 0; /* init array */ } for (month=1; month <= 12; month++) /* calc # days in month */

Some C Syntax Shortcuts Example 1: Standard x = x + 1; Shortcut x += 1; Even Better x++; Example 2: Standard x = x & 0xF; Shortcut x &= 0xF;

Almost Done!

Data Structures A data structure is a user-defined abstract data type. Used to group related data as a single unit (“object”). Programs containing data structures are conceptually easier to write, maintain, and understand. Algorithms (“methods”) are then written to perform operations on the abstract data type.

Data Structure Example struct database { int id_number; int age; float salary; }; int main() { struct database employee; /* There is an employee variable with modifiable variables inside it. */ employee.age = 22; employee.id_number = 1; employee.salary = 17500.21; promote( employee, 5000.); }

C Coding Style For readability, use block indentation Use descriptive variable names avoid keiths_var = 2.71828; One executable statement per line avoid: motor=100; if (switch_off) goto end; wait(ONE_SEC); Avoid highly nested function calls avoid: sqrt(1+(tan(1-hypot(PI*angle/180) << 2 * length)…. Provide useful comments avoid my_var = my_var + 1; //increment my_var

Bad Style! Q: What does this code do??? #include <stdio.h> main(t,_,a) char * a; { /*printf("main(%d,%d,\"%s\")\n",t,_,a);*/ return! 0<t? ( ( t<3? main(-79,-13,a+ main(-87,1-_, main(-86, 0, a+1 ) +a)): 1 ), ( t<_? main(t+1, _, a ) :3 ), ( main ( -94, -27+t, a ) &&t == 2 ? ( (_<13) ? main ( 2, _+1, "%s %d %d\n" ) :9 ) :16 ) : ( t<0? ( t<-72? main( _, t, "@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+,/+#n+,/#;\ #q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/+k#;\ q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){nl]!/n{n#'; \ r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\ n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c ;;\ {nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\ #'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/") ( t<-50? ( _==*a ? putchar(31[a]): main(-65,_,a+1) ) : main((*a == '/') + t, _, a + 1 ) ( 0<t? main ( 2, 2 , "%s") :*a=='/'|| main(0, main(-61,*a, "!ek;dc i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry") ,a+1) ) ; }

Answer: 12 Days of Christmas! On the first day of Christmas my true love gave to me a partridge in a pear tree. On the second day of Christmas my true love gave to me two turtle doves and a partridge in a pear tree. On the third day of Christmas my true love gave to me three french hens, two turtle doves On the fourth day of Christmas my true love gave to me four callaing birds, three french hens, two turtle doves On the fifth day of Christmas my true love gave to me five gold rings; On the sixth day of Christmas my true love gave to me six geese a-laying, five gold rings; On the seventh day of Christmas my true love gave to me sevean swans a-swimming, On the eighth day of Christmas my true love gave to me eight maids a-milking, sevean swans a-swimming, six geese a-laying, five gold rings; four callaing birds, three french hens, two turtle doves and a partridge in a pear tree. On the ninth day of Christmas my true love gave to me nine laadies dancing, eight maids a-milking, sevean swans a-swimming, On the tenth day of Christmas my true love gave to me ten lords a-leaping, On the eleventh day of Christmas my true love gave to me eleven pipers piping, ten lords a-leaping, On the twelfth day of Christmas my true love gave to me twelave drummers drumming, eleven pipers piping, ten lords a-leaping,

Common C Gotchas Forgetting == during equivalence checking: if (test_score = 93) /* WRONG! sets test_score to 93 */ printf (“Hooray\n”); if (test_score == 93) /* correctly compares test_score */ printf (“Hooray\n”); Best Method of Prevention: if (93 == test_score) C is case sensitive! unsigned char wheel_count; /* NOT the same as unsigned char Wheel_count; */

The best way to learn C is to write a program that does something useful! Happy Programming!