2. 2
Loops
• Loops cause a section of your program
to be repeated a certain number of
times
• Repeats until the condition remains true
• Terminates when the condition becomes
false
5. 5
The general format for a for loop
for (Initialization_action; Condition; Condition_update)
{
statement_list;
}
int n,f=1;
cin >> n;
for (i=2; i<=n; i++)
{
f *= i;
}
cout << “The factorial of ” << n << “ is ” << f << “.”;
1 2 3
Factorial of n is n(n-1)(n-2)...21
6. 2-while loop
• for loop does something a fixed number of times.
• If you don’t know how many times you want to do
something before you start the loop?
• In this case a different kind of loop may be used:
the while loop
8. while loop - syntax
Loop body contain
single statement
Loop body contain
Multiple statement
9. 3-do loop
• In while loop if condition is false it is never entered
or executed
• Sometime, requirements are that the loop should
be executed at least once….
• For that, we use do loop, that guarantees at least
on execution of the loop body
10. do while loop - syntax
Loop body contain
single statement
Loop body contain
Multiple statement
11. 11
do-while
Condition
Statement
list
T
F
do
{
Statement list
} while (Condition);
string ans = “n”;
while (ans != “Y”)
{
cout << “Would you marry me?”;
cin >> ans;
}
cout << “Great!!”;
; is required
do
{
cout << “Would you marry me?”;
cin >> ans;
} while (ans != “Y”);
cout << “Great!!”;
12. Conclusion
C++ provides three different loops for
eliciting repetitive behavior.
Which one is best to solve a given
problem depends on the algorithm for
that problem.