05 - C Basics - Control Structures - Part 2 - Loops (While, Do While, For)
05 - C Basics - Control Structures - Part 2 - Loops (While, Do While, For)
05 - control structures
part 2
Loops (while, do while, for) /AhmedHatemS
/c/AhmedHatemS
What is the content?
1. Repetition control structures.
➢ While loop
➢ Do .. while loop
➢ For loop
2. Notes
5. Sentinel-control repetition.
start
Program to take 10 grades
from a student and print Counter = 1, grade,
the average of them. sum = 0;
no
Counter <= 10 ?
yes
Get grade
Print sum/10;
end
do .. While loop
• We use it when we want to do an action once before checking the
condition.
Notes
• Off-by-One Error:
If you wrote counter < 10 instead counter <= 10, then the loop will be
executed only 9 times.
counter += 1;
++count;
count++;
Thus, are all equivalent.
• Both expression 1 and expression 3 are comma-separated lists:
for ( x = 0 , y = 0 ; x <= 10 ; x++ , y += 2 )
The commas as used here are comma operators ..
Expression 2:
- C++ assumes that the condition is true → infinite loop
- Expression 3:
- - If the increment is in the for’s body, or if it’s needed.
Program to
find
remainder
and quotient
Dividend , divisor, quotient,
remainder
Break & continue statements.
• The break statement, when executed in a:
while, for, do .. while, or switch .. case statement ..
causes an immediate exit from that statement.
Program execution continues with the next/following statement.
Common uses of the break statement are to escape early from a loop, or to skip the
remainder of a switch statement.
• The continue statement, when executed in a while, for, or a do
.. while statement, skips the remaining statements in the body
of that control statement, and then performs the next iteration of
the loop.
Next video