Loops Method for getting a sequence of statements to be repeated. Many different ways of writing loops. Concentrate on two: counting loops and sentinel-controlled loops. Counting loops: set the "count of items processed" to 0 do the following n times (n is a data value) read a number square it display the number and its square add 1 to "count of items processed" In a counter controlled loop, there is a special program variable, the counter, that counts the number of loop executions so far. Counter is set to an initial value of 0. When this count reaches some prespecified maximum, the loop is "exited" - loop repetition stops. The part that is repeated (the loop body) is indented in above pseudocode. Sentinel-controlled loops: read a data value while the data value read is not the sentinel process the last data value read in some way read the next data value In a sentinel controlled loop, there is an "extra" data value called the sentinel. For example, exam scores might be 75, 80, 90. The data would be entered as 75, 80, 90, -1 where -1 is the sentinel. The loop body (indented) continues to execute until the sentinel value is read. Implementing loops: We will study 2 loop forms in C, while statement and for statement. while statement: while (condition) { statement1; statement2; . statementn; } or while (condition) statement; 1. Evaluate the condition. 2. If the condition is true, execute the loop body (between braces or next statement if no braces). If the condition is false, exit the loop. 3. Repeat steps 1 and 2 until loop exit occurs. Implement a counting loop using a while statement int count; double x, xSquared; int numX; /* input */ printf("How many items to process>"); scanf("%d", &numX); count = 0; while (count < numX) { printf("Enter next number to square>"); scanf("%lf", &x); xSquared = x * x; printf("The square of %f is %f\n", x, xSquared); count = count + 1; } while statement implementation of sentinel loop int score; int sentinel = -1; printf("Enter first score>"); scanf("%d", &score); while (score != sentinel) { process(score); /* call function process */ printf("Enter next score>"); scanf("%d", &score); } Class examples: Write a loop that finds the sum of the first n integers where n is a data item. Display the final sum. (counting or sentinel?) int int int scanf( ); ____ = 0; while ( ) { ____ = ____ + 1; } printf( ); Write a loop that reads a series of numbers and calculates their product. Display the final product. The calculation should stop when the number 0 is read. (counting or sentinel?) double double double _______ = _____; scanf( ); while ( ) { _______ = _______ * ________; scanf( ); } Write a loop that reads up to 10 numbers and calculates their product. Display the final product. The calculation should stop when the 10th number is read or the number 0 is read. (counting or sentinel?) double double double int scanf( ); ______ = ______; while ( && ) { _______ = _____ * ______; _______ = _____ + _____; scanf( ); }