L4 - Loop
L4 - Loop
Loop
1
Ahmed Farhan Ahnaf Siddique
Assistant Professor,
Department of Civil Engineering,
BUET
2
Statement Blocks
• A statement block is a sequence of statements
enclosed by braces{ }, like this:
7
The while Statement
#include <iostream>
using namespace std;
int main()
{
int n, i=1;
cout << "Enter a positive integer: ";
cin >> n;
long sum=0;
while (i <= n)
sum += i++;
cout << "The sum of the first " << n << "
integers is " << sum << endl;
}
8
The do … while Statement
• The syntax for the do ... while statement is
do {statement;}
while (condition); 9
The do … while Statement
10
The do … while Statement
#include <iostream>
using namespace std;
int main()
{
long bound;
cout << "Enter a positive integer: ";
cin >> bound;
cout << "Factorial numbers < " << bound <<
":\n1,1";
long f=1,i=1;
11
The do … while Statement
do
{
f *= ++i; Can you
correct this
cout << "," << f;
program?
}
while (f < bound);
}
• The do … while loop iterates until its control
condition (f < bound) is false.
Output:
Enter a positive integer: 1000000
Factorial numbers < 1000000:
1,1,2,6,24,120,720,5040,40320,362880,3628800
12
The for Statement
• The syntax for the for statement is
14
The for Statement
17
The for Statement
#include <iostream>
using namespace std;
int main()
{
for (int m=95, n=11; m%n > 0; m -= 3, n++)
cout << m << "%" << n << " = " << m%n << endl;
}
Output:
95%11 = 7
92%12 = 8
89%13 = 11
86%14 = 2
83%15 = 8 18
The for Statement
#include <iomanip> // defines setw()
#include <iostream>
using namespace std;
int main()
{
for (int x=1; x <= 12; x++)
{
for (int y=1; y <= 10; y++)
cout << setw(4) << x*y;
cout << endl;
}
}
19
The continue Statement
• The break statement skips the rest of the statements
in the loop’s block, jumping immediately to the next
statement outside of the loop.
20
The continue Statement
#include <iostream>
using namespace std;
int main()
{
int n;
for (;;)
{
cout << "Enter int: "; cin >> n;
if (n%2 == 0) continue;
if (n%3 == 0) break;
cout << "\tBottom of loop.\n";
}
cout << "\tOutside of loop.\n";
} 21
The goto Statement
• The goto statement is another kind of jump
statement, its destination is specified by a label
within the statement.
22
The goto Statement
#include <iostream>
using namespace std;
int main()
{
const int N=5;
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
for (int k=0; k<N; k++)
{
if (i+j+k>N) goto esc;
else cout << i+j+k << " ";
}
cout << "* ";
}
esc: cout << ". " << endl; //inside i loop, outside j loop
}
} 23
The goto Statement
Output:
01234*12345*2345.
12345*2345.
2345.
345.
45.
25
The goto Statement
• But then on the next iteration of the k loop, i = 0, j =
2, and k = 4, so i+j+k = 6, causing the goto statement
to execute for the first time.
• Note that both the k loop and the j loop are aborted
before finishing all their iterations.