 # 1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld.

## Presentation on theme: "1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld."— Presentation transcript:

1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld

2 Declaration  Creating an identifier and associating it with a type and (behind the scenes) a location in memory. A couple of examples: int integer1; int integer1, integer2, sum;  integer1, integer2 and sum are all variables

3 Data Types  C (as well as many other programming languages) are very sensitive to data type.  The int family short, long  The float family Double  Characters (strings)

4 Conversion Specifiers  %d – integer  %f – float  %c – character  %s - string

5 Arithmetic in C  The C arithmetic operators are + for addition - for subtraction * for multiplication / for division, and % for modulus

6 Parentheses  Are your friends  Are your really good friends  Because with them you can ensure expressions are evaluated as you expect  Can avoid mistakes with operator precedence (one less thing to think about) e.g. y = m * x + b ; y = (m * x) + b; e.g. y = a * b * b + c * b – d; y = ((((a * b) * b) + (c * b)) – d);

7 Old Example #include int main() { int num1, num2; num1= 3; num2 = 2; //also int num1=3, num2=2; printf("%d plus %d equals %d\n", num1, num2, num1+num2); }

8 Program Example #2 #include int main() { int num1=3, num2=2; printf("%d\n", num1*num2/(num1+num2)-num2*2+num1+1); //The answer is 1 return 0; }

9 Program #3 #include int main() { printf("%d\n",2*3%4-1-1*2/3); //It's one return 0; }

10 Interactive Input (scanf) #include int main() { int integer1, integer2, sum; /* declaration */ printf( "Enter first integer\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */ printf( "Enter second integer\n" ); /* prompt */ scanf( "%d", &integer2 ); /* read an integer */ sum = integer1 + integer2; /* assignment of sum */ printf( "Sum is %d\n", sum ); /* print sum */ return 0; /* indicate that program ended successfully */ }

11 Program #5 #include int main() { int integer1, total; printf( "Enter a value for X \n" ); scanf( "%d", &integer1 ); total = 3*integer1*integer1*integer1 + 2*integer1*integer1+1; printf( "The answer is %d\n", total ); return 0; }

12 The Modulus Operator #include int main() { int num1, num2; printf( "Enter a value for the numerator \n" ); scanf( "%d", &num1 ); printf( "Enter a value for the divisor \n" ); scanf( "%d", &num2 ); printf("%d goes into %d %d times with a remainder of %d\n", num2, num1, num1/num2, num1%num2); return 0; }

13 Programs to think about….  Deitel p. 54 ex. 2.25 (displaying initials)  Deitel p. 55 ex. 2.31 (displaying square info)  Calculating the average of 4 numbers

Download ppt "1 Introduction to Computers and Programming Class 3 Introduction to C Professor Avi Rosenfeld."

Similar presentations