Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island
Data Types Basic Types Enumerated types The type void Derived types Types Description They are arithmetic types: (a) Integer types, (b) floating-point types They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values. (keyword: enum) The type specifier void indicates that no value is available. (a) Pointer types, (b) Array types, (c ) Structure types
Integer Types Type Storage size Value range char 1 byte -128 to 127 or 0 to 255 unsigned char 1 byte 0 to 255 signed char 1 byte -128 to 127 int 2 or 4 bytes -32,768 to 32,767 or - 2,147,483,648 to 2,147,483,647 unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 short 2 bytes -32,768 to 32,767 unsigned short 2 bytes 0 to 65,535 long 4 bytes -2,147,483,648 to 2,147,483,647 unsigned long 4 bytes 0 to 4,294,967,295
Floating-Point Types Type Storage size Value range Precision float 4 byte 1.2E-38 to 3.4E+38 6 decimal places double 8 byte 2.3E-308 to 1.7E+308 15 decimal places long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places
Enumerated types (Examples) enum Boolean { false; true; Boolean b; enum Color { red; orange; yellow; green; cyan; blue; violet; Color c; enum Degree { PhD; master; bachelor; associate; Degree d;
Array An array is a collection of data elements that are of the same type (e.g., a collection of integers, collection of characters, collection of doubles). Syntax: <type> <arrayname> [<array_size>] E.g., double grade[10] = {80, 85, 60, 75, 88, 95, 69, 78, 74, 96 ; 0 1 2 3 4 5 6 7 8 9 Grade 80 85 60 75 88 95 69 78 74 96
Array (Cont ) #include <stdio.h> /* calculate the average grade */ int main() { double grade[10] = {80, 85, 60, 75, 88, 95, 69, 78, 74, 96 ; int i; // array index double AvgGrade = 0; for (i = 0; i < 10; i++) { AvgGrade = AvgGrade + grade[i]/10; printf( Average grade = %4.2f\n, AvgGrade);
Two-Dimensional Array Syntax: <type> <arrayname> [<array_x_size>] [<array_y_size>] E.g., int image[4][4]={{0,1,1,0, {1,1,0,0, {0,1,0,1,{0,0,1,1; Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 Row 3 0 1 1 0 1 1 0 0 0 1 0 1 0 0 1 1
Operators Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators Misc Operators
Arithmetic Operators Operator Description Example + Adds two operands. A + B = 30 Subtracts second operand from the first. A B = -10 * Multiplies both operands. A * B = 200 / Divides numerator by denumerator. % Modulus Operator and remainder of after an integer division. ++ Increment operator increases the integer value by one. -- Decrement operator decreases the integer value by one. B / A = 2 B % A = 0 A++ A--
Relational Operators Operator Description Example == Checks if the values of two operands are equal or not. If yes, then the condition becomes true.!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. > Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. < Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A == B) is not true. (A!= B) is true. (A > B) is not true. (A < B) is true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true.
Logical Operators Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. Called Logical OR Operator. If any of the two operands is nonzero, then the condition becomes true.! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. (A && B) is false. (A B) is true.!(a && B) is true.
Bitwise Operators p q p & q p q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1
Bitwise Operators (Cont ) Operator Description Example & Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., 0000 1100 Binary OR Operator copies a bit if it exists in either operand. (A B) = 61, i.e., 0011 1101 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. (A ^ B) = 49, i.e., 0011 0001 (~A ) = -61, i.e,. 1100 0011 in 2's complement form. A << 2 = 240 i.e., 1111 0000 A >> 2 = 15 i.e., 0000 1111
Assignment Operators Operator Description Example = Simple assignment operator. C = A + B will assign the value of A + B to C += Add AND assignment operator. C += A is equivalent to C = C + A -= Subtract AND assignment operator. C -= A is equivalent to C = C - A *= Multiply AND assignment operator. C *= A is equivalent to C = C * A /= Divide AND assignment operator. C /= A is equivalent to C = C / A %= Modulus AND assignment operator. C %= A is equivalent to C = C % A <<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 = Bitwise inclusive OR and assignment operator. C = 2 is same as C = C 2
Misc Operators Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a;? : Conditional Expression. If Condition is true? then value X : otherwise value Y
Operator Precedence 17
Conditional Statements if (expression) statement1 else statement2 else is optional expression is evaluated execute statement1 if TRUE, statement2 if FALSE if (expression1) statement1 else if (expression2) statement2 else statement3 expression2 is evaluated if expression1 is FALSE
Conditional Example #include <stdio.h> int main() { int x = 1; if(x==1) printf( Correct.\n ); else printf( Incorrect.\n );
Switch switch (expression) { case const_expr1: statement1 case const_expr2: statement2 default: statement3 expression is evaluated, compared to const_expr Statements are executed corresponding to the first matching expression default is optional
Break in a Switch Without a break statement, the case will not end If x==0 then both y=1; and y=2; are executed switch (x) { case 0: y = 1; case 1: y = 2; break; case 2: y=3;
While and For Loops for (expr1; expr2; expr3) { statement; expr1; while (expr2) { statement; expr3; expr1; do { statement; expr3; while (expr2); Initialization and increment are built into the for loop Condition checked at the top of a for/while loop Condition checked at the bottom of a do-while loop
While Example #include <stdio.h> int main() { int i = 0; while(i < 3) { printf( %d, i); i = i + 1; Three passes through the loop: i = 0, 1, 2 Exits loop when i=3
All Built Into the For Statement #include <stdio.h> int main() { int i; for (i = 0; i < 3 ; i++) { printf( %d, i); initialization termination step
Break and Continue Break jumps to the end of a for, while, do, or case while (x > 5) { y++; if (y < 3) break; x++; Continue jumps to the next iteration of a loop while (x > 5) { y++; if (y < 3) continue; x++;
Functions /* function returning the max between two numbers*/ int max(int num1, int num2) { int result; if(num1 > num2) result = num1; else result = num2; return result; #include <stdio.h> /*function declaration*/ int max(int num1, int num2); int main() { int a = 100; int b = 200; int ret; ret = max(a,b); Function call printf( Max value is : %d\n, ret); return 0; Function definition 26
Examples bool FPGALedSet (int mask) // set the 10 LEDs based on x 000 x 3FF 0 bool HexSet(int index, int value) //set sevseg display to a 5 6 1 hex value 0 F 4 2 bool SwitchRead(uint32_t *mask) // sets a mask to the binary value of the switches 3
How to Get User Input from Command Line #include <stdio.h> int main(int argc, char *argv[]){ int i; if(argc <2){ printf("no input! "); else{ for(i=0; i<argc; i++){ printf("%s ", argv[i]); printf("\n"); return 0;
How to Generate Random Numbers #include <stdio.h> #include <stdlib.h> int main() { int c, n; printf("ten random numbers in [1,100]\n"); for (c = 1; c <= 10; c++) { n = rand() % 100 + 1; printf("%d\n", n); return 0;
Local Variables void foo () { int i;. A variable is local if it s defined inside a function They can be used only by statements that are inside that function or block of code.
Global Variables int global_i void foo () { extern int global_i;. A variable is global if it s defined outside of any function A global variable must be declared as an extern in any function using it Extern not needed if global declaration is before the function Variables can be global across files
Globals Are Dangerous void foo () { extern int global_i;. global_i = a + b c ; int bar () { extern int global_i;. x = global_i *. Global variables can propagate bugs Bug in foo can cause bar to crash Debugging can become harder Reduce modularity of code
Preprocessor Directive #define #include #undef #ifdef #ifndef #if #else #elif #endif #error #pragma Description Substitutes a preprocessor macro. Inserts a particular header from another file. Undefines a preprocessor macro. Returns true if this macro is defined. Returns true if this macro is not defined. Tests if a compile time condition is true. The alternative for #if. #else and #if in one statement. Ends preprocessor conditional. Prints error message on stderr. Issues special commands to the compiler, using a standardized method.
Preprocessor Examples #include <stdio.h> # include myheader.h #ifndef MESSAGE #endif #define MESSAGE You wish #Undef FILE_SIZE #Define FILE_SIZE 42 #ifdef DEBUG /* Your debugging statements here*/ #endif