SiteBanner

Looping in 'C' is a matter of designating 1) a single statement or 2) a group of statements (encapsulated with '{' and '}' braces) that are executed repeatedly a prescribed number of times.  There are 3 frequently-used looping constructs:  'while()', 'for()", and "do while ()".  Let's play with these. 

 

(right-click to download)

/* pgm7 source */

#include <stdio.h>

int main(void) {
int teeth;
int pennies;
int rabbits;
int z;

printf("\n\n");

teeth = 20; // as a baby
pennies = 0; // we're broke
rabbits = 0;

printf("Baby Maude was born with %d teeth.\n", teeth);
while (teeth > 0) {
    teeth--; // '--' means decrement, or "subtract one from the value"
    teeth--;
    teeth--;
    printf("Last month she lost 3. Now she has %d\n", teeth);
    }

printf("\nIf I received 231 pennies every month for 1 year, how many would I have each month?\n");
do {
    pennies += 231;
    z++;     // '++' means increment, or "add one to the value"
    printf("Month %d : %d pennies\n", z, pennies);
    } while (z < 12);

printf("\n");

for (rabbits = 1; rabbits < 11; rabbits++) // for ("initial value" -- "test to perform" -- "what happens each loop"
    printf("Rabbits: %d\n", rabbits);
printf("\nEeek! Too many rabbits!\n");

printf("\n\n");
return(0);
}

 

Part and parcel of loops is INCREMENTING and DECREMENTING.  Every time 'value--;' is executed, the number in 'value' is subtracted by one.  Likewise, 'count++' adds one to 'count' each execution of the line.  In future we'll see how 'count++' and '++count' ARE different considerations.  If a loop construct only acts upon ONE statement, no encapsulating '{' and '}' are needed (as seen in the 'for ()' loop).