Loops in C++
By Rizwan Ullah
Class: BSSE (2nd)
Course: Object Oriented Programming
Loops in C++
In Programming, sometimes there is a need to perform some
operation more than once or (say) n number of times. Loops
come into use when we need to repeatedly execute a block of
statements.
For example: Suppose we want to print “Pakistan” 10 times.
This can be done in two ways as shown below:
Manual Method (Iterative Method)
• Manually we have to write cout for the C++ statement 10
times. Let’s say you have to write it 20 times (it would surely
take more time to write 20 statements) now imagine you have
to write it 100 times, it would be really hectic to re-write the
same statement again and again. So, here loops have their
role.
// C++ program to Demonstrate the need of loops
#include <iostream>
using namespace std;
int main()
{
cout << "Pakistan\n";
cout << "Pakistan\n";
cout << "Pakistan\n";
cout << "Pakistan\n";
cout << "Pakistan\n";
return 0;
}
Types of Loops:
• There are three types of loops.
• For Loop
• While Loop
• Do-while Loop
For Loop
• A For loop is a repetition control structure that allows us to
write a loop that is executed a specific number of times. The
loop enables us to perform n number of steps together in one
line.
• Firstly initializes, then, condition check, execute body, update.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Example1:
for(int i = 0; i < n; i++)
{
// BODY
}
Flow Diagram of for loop:
Example1:
// C++ program to Demonstrate for loop
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++) {
cout << "Welcome to FOC\n";
}
return 0;
}
While Loop
• First checks the condition, then executes the body.
• We have already stated that a loop mainly consists of three
statements – initialization expression, test expression, and
update expression. The syntax of the three loops – For, while,
and do while mainly differs in the placement of these three
statements
Syntax:
initialization expression;
while (test_expression)
{
// statements
update_expression;
}
Flow Diagram of while loop:
Example:
// C++ program to Demonstrate while loop
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
cout << "I am a student\n";
// update expression
i++;
}
return 0;
}
Do-while loop
• Firstly, execute the body then condition check.
Syntax:
initialization expression;
do
{
// statements
update_expression;
} while (test_expression);
Flow Diagram of for loop:
// C++ program to Demonstrate do-while loop
#include <iostream>
using namespace std;
int main() {
int i = 2; // Initialization expression
do {
// loop body
cout << "Hello World\n";
// update expression
i++;
} while (i < 1); // test expression
return 0;
}