PF Ue Lec 5
PF Ue Lec 5
(COMP1112)
Lecture 4
Repetition Structure
// outer loop
for (int i = 2; i <= table; i++)
{
for (int j =1 ; j <= max; j++) // inner loop
{
cout<< i*j;
}
cout<<“\n”;
}
}
While Loop
while (condition) {
statements;
}
If a condition is true then and only then the body of a loop is executed.
After the body of a loop is executed then control again goes back at the
beginning, and the condition is checked if it is true, the same process is
executed until the condition becomes false. Once the condition becom
es false, the control goes out of the loop.
Example
int num =0;
while (num<=10)
{
cout<<num;
num++;
}
do while loop
do
{
Statements
} while (expression);
• A do-while loop is similar to the while loop except that the condition is
always executed after the body of a loop. It is also called an exit-controlled
loop.
• The body is executed if and only if the condition is true. In some cases, we
have to execute a body of the loop at least once even if the condition is
false.
Example
int num =1;
do {
cout<<2*num;
num++;
} while (num<=10);
Break Statement
• The break statement is used in the switch statement. It is also useful for immediately stopping a
loop.
int main()
{
int num = 5;
while (num > 0)
{
if (num == 3)
break;
cout<<num;
num--;
}
}
Continue Statement
• When you want to skip to particular iteration but remain in the loop, you should
use the continue statement.
int main()
{
int nb = 7;
while (nb > 0)
{ nb--;
if (nb == 5)
continue;
cout<<nb;}
}
Example: C++ code to find the sum of first n
natural numbers till the positive integer entered
by user
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
• Object oriented programming using C++ by Tasleem Mustafa, Imran Saeed, Tariq Mehmood, Ahsan Raza
• https://www.tutorialspoint.com/cplusplus
• http://ecomputernotes.com/cpp/introduction-to-oop
• http://www.cplusplus.com/doc/tutorial
• https://www.programiz.com
• https://www.guru99.com/c-loop-statement.html