PF Lab Manual 5
PF Lab Manual 5
Engineering
Faculty of Engineering & Applied Sciences
Riphah International University, Islamabad, Pakistan
while loop
1. – First checks the condition, then executes
the body.
for loop
2. – firstly initializes, then, condition check,
execute body, update.
do-while
loop
3.
– firstly, execute the body then condition
check
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.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
Explanation of the Syntax:
Initialization statement: This statement gets executed only once, at the beginning of the for
loop. You can enter a declaration of multiple variables of one type, such as int x=0, a=1, b=2.
These variables are only valid in the scope of the loop. Variable defined before the loop with
the same name are hidden during execution of the loop.
Condition: This statement gets evaluated ahead of each execution of the loop body, and abort
the execution if the given condition get false.
Iteration execution: This statement gets executed after the loop body, ahead of the next
condition evaluated, unless the for loop is aborted in the body (by break, goto, return or an
exception being thrown.)
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++) {
cout << "Hello World\n";
}
return 0;
}
While Loop-
While studying for loop we have seen that the number of iterations is known beforehand, i.e. the
number of times the loop body is needed to be executed is known to us. while loops are used in
situations where we do not know the exact number of iterations of the loop beforehand. The loop
execution is terminated on the basis of the test conditions.
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;
}
Example
#include <iostream>
using namespace std;
int main()
{
// initialization expression
int i = 1;
// test expression
while (i < 6) {
cout << "Hello World\n";
// update expression
i++;
}
return 0;
}
Tasks :
3. Write a program in C++ to display n terms of natural numbers and their sum.