1.8 Flow Control - Loops
1.8 Flow Control - Loops
Repetition in Programs
Three types of program control structure:
2 Loops 2/22/2024
We refer to each time an action is repeated as an iteration. 1) Fixed Count Loops: Repetition over a finite set (for loops).
We continue repeating the action until a terminating condition is satisfied. 2) Variable Count Loops: Repetition as long as a given condition
This terminating condition is called a loop guard holds (while and do-while loops).
The loop guard is represented by a boolean expression in the same way as Loops can be further classified as being either pre-test (while loops)
1
2/22/2024
6 Loops 2/22/2024
change (update) of the loop control variable i < 10 is the loop guard i.e. repeat until i is greater or equal to 10
/* Display nonnegative numbers < max */ i = i +1; this is the counter increment ; it is more commonly written i
2
2/22/2024
for (counter = 0; counter < limit; ++counter) The general syntax of a while loop is
++ comes immediately after the operand Terminate when the expression evaluates to false
expression’s value is the value of the variable before it is incremented
3
2/22/2024
with a semicolon (the other loops should not be terminated with a 2:Write a program which continually reads in integers until 45 is read in
semicolon, adding to the confusion). 3: Use a Do while loop to calculate the minimum of 100 integers being
Notice that this loop will execute once, because it automatically executes read in.
before checking the condition.
15 Loops 2/22/2024
4
2/22/2024
5
2/22/2024
While (counter < 100) 5: Write a program to
{ printf(“enter no”);
scanf(“%d", &x); calculate
( X 2n )
If (x < min) min = x;
N 1
counter++;}
printf(“minimum is %d”,min);
}
6
2/22/2024
7
2/22/2024
prefix increment Write C code to print the information contained in each of the slides that
postfix increment
8
2/22/2024
9
2/22/2024
END
37 Loops 2/22/2024
10