<<

Syntax of the while statement

while (condition){ statement(s) } Loops For while statements „ condition is a true/false (non-zero/zero) expression „ If condition is initially false, the statement is never executed „ If condition is true, statement(s) is executed and condition is re-evaluated

Based on slides © McGraw-Hill „ One of the statements should eventually make the loop Additional material © 2004/2005 Lewis/Martin Modified by Diana Palsetia stop

CIT 593 1 CIT 593 2

Infinite Loops A while Loop to Print Numbers The following loop will never terminate: int x = 0; while (x < 10) { // Print the numbers 1 thru 10 printf(“%”,x); int x = 1; } while (x <= 10){ Loop body does not change condition... printf(“%d”, x); „ ...so test is never false x = x + 1; „ Common programming error that can be difficult to find } Sometimes you might start out with true case: int x = 1; while(x){ „ What happens if you forget the statement x = x + 1 ? //remember that there is no boolean type in „ We print value 1 forever //make x to 0, so the loop terminates „ Known as }

CIT 593 3 CIT 593 4

1 While vs. For for (init; end-test; re-init){ statement Code Explanation } int x = 1; An example of a while (x <= 10){ while loop that prin tf(“%d”,x ); has this For loop: pattern x = x + 1; „ Executes loop body as long as end-test evaluates to TRUE } „ Initialization and re-initialization code included in loop statement

Note: Test is evaluated before executing loop body int x; A for loop that for (x = 1; x <= 10; x = x + 1){ does the same Difference in Java vs. C printf(“%d”,x); thing „ Loop variable in C needs to be declared outside the for } statement

CIT 593 5 CIT 593 6

Example For Loops For vs. While /* -- what does this one output? -- */ In general: char letter = 'a'; int c; For loop is preferred for counter-based loops for (c = 0; c < 26; c++) { printf(" %c\n", letter+c); „ Explicit counter variable } „ Easy to see how counter is modified each loop

/* -- what does this loop do? -- */ While loop is preferred for sentinel-based loops int numberOfOnes = 0; „ E.g. eof = end of file or \n = newline character int bitNum; for (bitNum = 0; bitNum < 16; bitNum++) { Note: Either kind of loop can be expressed as other, so its if (inputValue & (1 << bitNum)) { really a matter of style and readability numberOfOnes++; } }

CIT 593 7 CIT 593 8

2 Do-While do{ statement(s); } loop_body while (condition);

test T F Do-while „ Executes loop body as long as test evaluates to TRUE (non- zero). „ Note: Test is evaluated after executing loop body. Therefore the statements inside the loop body are executed at least once

CIT 593 9

3