|
/*Counter-controlled repetition, print numbers from 1 to 10 */ #include <stdio.h> int main() { int counter = 1; /* initialization */ while ( counter <= 10 ) { /* repetition condition */ printf ( "%d\n", counter ); ++counter; /* increment */ } return 0; } |
/*Counter-controlled repetition with the for structure ,print numbers
from 1 to 10 */ #include <stdio.h> int main() { int counter; /* initialization, repetition condition, and increment are all included in the for structure header */ for ( counter = 1; counter <= 10; counter++ ) printf( "%d\n", counter ); return 0; } |
| /*
Using the do/while repetition structure ,print numbers from 1 to 10 */ #include <stdio.h> int main() { int counter = 1; do { printf( "%d ", counter ); } while ( ++counter <= 10 ); return 0; } |
/* calculate the
sum of even numbers between 2 and 100 */
#include <stdio.h> |
| /*
Using the break statement in a for structure */ #include <stdio.h> int main() { int x; for ( x = 1; x <= 10; x++ ) { if ( x == 5 ) break; /* break loop only if x == 5 */ printf( "%d ", x ); } printf( "\nBroke out of loop at x == %d\n", x ); return 0; } |
/*Using the
continue statement in a for structure */ #include <stdio.h> int main() { int x; for ( x = 1; x <= 10; x++ ) { if ( x == 5 ) continue; /* skip remaining code in loop only if x == 5 */ printf( "%d ", x ); } printf( "\nUsed continue to skip printing the value 5\n" ); return 0; } |
| /*
Calculating compound interest */ #include <stdio.h> #include <math.h> int main() { int year; double amount, principal = 1000.0, rate = .05; printf( "%4s%21s\n", "Year", "Amount on deposit" ); for ( year = 1; year <= 10; year++ ) { amount = principal * pow( 1.0 + rate, year ); printf( "%4d%21.2f\n", year, amount ); } return 0; } |
/*Print a shape */
#include <stdio.h> |
| /*
Counting letter grades until the user press
ctrl +d (=EOF) */ #include <stdio.h> int main() { int grade; int aCount = 0, bCount = 0, cCount = 0, dCount = 0, fCount = 0; printf( "Enter the letter grades.\n" ); printf( "Enter the EOF character to end input.\n" ); while ( ( grade = getchar() ) != EOF ) { switch ( grade ) { /* switch nested in while */ case 'A': case 'a': /* grade was uppercase A */ ++aCount; /* or lowercase a */ break; case 'B': case 'b': /* grade was uppercase B */ ++bCount; /* or lowercase b */ break; case 'C': case 'c': /* grade was uppercase C */ ++cCount; /* or lowercase c */ break; case 'D': case 'd': /* grade was uppercase D */ ++dCount; /* or lowercase d */ break; case 'F': case 'f': /* grade was uppercase F */ ++fCount; /* or lowercase f */ break; case '\n': case' ': /* ignore these in input */ break; default: /* catch all other characters */ printf( "Incorrect letter grade entered." ); printf( " Enter a new grade.\n" ); break; } } printf( "\nTotals for each letter grade are:\n" ); printf( "A: %d\n", aCount ); printf( "B: %d\n", bCount ); printf( "C: %d\n", cCount ); printf( "D: %d\n", dCount ); printf( "F: %d\n", fCount ); |