C Programming IV

Dr. Sorin Draghici
Wayne State University


http://www.cs.wayne.edu/~sod/course.html


Summary


Implicit type conversions and casts
Arrays
Loops
for
while
do


Implicit (automatic) type conversions

The compiler performs 'automatic' type conversions every time there is an operation between two different types. The 'smaller' type will be brought to the 'larger' one.

float x = 1.5 ;
int y = 2 ;
double result ;

result = x * y ; /* result will be 3. as a double*/


Casts

A cast is an explicit type conversion: the programmer requires the compiler to interpret a given type as a different one.

float x ;
int a, b ;
a = 3 ;
b = 2 ;
x = a/b ; /* x = 1. */

x = (float)a/b ; /* x = 1.5 */


Arrays

An array is a data structure used to store several elements of the same type. Accessing one particular element is done through indexing the name of the array.
int table[10] ; /* table is an array of 10 integers */
table[3] = 2 ;

y = table[3] ;

Loops

The 'while' loop (entry-condition)

while ( condition )
statement

Examples:
i = 0 ;
while( i < 10 )
scanf("%d", &a[i++] ) ;


Loops

The 'do-while' loop (exit condition)
while ( condition )
statement

Examples:
i = 0 ;
do
scanf("%d", &a[i++] ) ;
while ( i < 9 ) ;


Loops

The 'for' loop (entry condition)

for( initialize ; condition; increment )
statement


Examples:

for( i = 0 ; i < 10 ; i++ )
scanf("%d", &a[i] ) ;


Remember!

The syntax of any loop specifies exactly ONE statement in the body of the loop.

Example:

x = 1 ;
while ( x < 10 )
printf("%d\n", x ) ;
x++ ;
printf("I'm done\n") ;

Remember!!

A statement is an expression ended with ;
Example:

int x[10], y[10] ;
for( i = 0 ; i < 10 ; i++ )
x[i] = y[i] ;

for( i = 0 ; i < 10 ; x[i] = y[i++] )
;

Remember!!!

for( i = 0 ; i < 10 ; x[i] = y[i++] )
;

for( i = 0 ; i < 10 ; x[i] = y[i++] ) ;

int a[10], b[10] ;
for( i = 0 ; i < 10 ; i++ ) ;
x[i] = y[i] ;

i = 0 ;
while( x < 10 ) ;
printf("%d\n", x ) ;


Conditions

The 'conditions' are nothing but expressions.
Usually they are logical expressions like:
( x>0 && y>0 )
A logical expression is constructed with logical operators like:
&&, ||, !
…and relational operators like:
<, <=, >, >=, ==, !=


But...

Remember that in C, any expression has a value. Furthermore, in C:
'false' is zero and
'truth' is any non-zero value.

Example:

y = 1 ; x = 7 ;
if ( x = y )
printf("%d\n", x ) ;
else
printf("%d\n", y ) ;


Remember!!!

Don't confuse '=' with '=='
'=' is the assignment operator
'==' is the equality test operator
Don't use one when you need the other.


Summary

Implicit type conversions and casts
Arrays
Loops
for
while
do


Reading

Chap. 6 (pg. 160-203) and 7 (pg. 206-248)
Don't forget the review questions:
chap. 6, pg. 200-202
chap. 7, pg. 245-247