Loops in C++
Loops in C: A type of control structure that repeats statements or set of statements is known as a looping structure. It is also known as iterative or repetitive structures. In a sequential structure, all statements are executed once. On the other hand, conditional structures may execute or skip a statement based on some given condition. In some situations, it is required to repeat a statement or number of statements for a specified number of times. Looping structures are used for this purpose. There are different types of loops available in C++. while loop do-while and for loop etc.
Loops are used for two purposes:
- To execute a statement or number of states for a specified number of times. For example, a user may display his name on screen 15 times.
- To use a sequence of values. For example, a user may display a set of natural. numbers from 1 to 15.
There are three types of loops available in C++. These are as follows:
- while loop do-while loop • for loop
Counter-Controlled Loops
In C++ the loops, This type of loop depends on the value of a variable known as counter variable The value of a counter variable is incremented or decremented earth time the buds of the loop are executed. This loop terminates when the value of counter variables reaches a particular value. The number of iterations of the counter-controlled loop is known in advance. The iterations of this loop depend on the following:
- The initial value of the counter variable
- Terminating condition
- Increment or decrement value
Sentinel-Controlled Loops
In C++ the loops These types of loop depend on special values known as the sentinel value. The loop terminates when the sentinel values are encountered. These types of the loop are also known as the conditional loop. For example, a loop may execute while the value of a variable is not -L Here -1 is the sentinel value that is used to terminate the loop
The number of iterations of the sentinel-controlled loop is unknown. it depends on the input from the user. Suppose the sentinel value to terminate a loop is -1. if the user enters -1 in the first iteration, the loop will execute only once. But if the user enters-1 after entering many other values, the number of iterations will vary accordingly. A sentinel value is commonly used with while and do-while loops.
while Loop
While-loop is the simplest loop of C++ language. While-loop executes one or more statements while the given condition remains true. It is useful when the number of iteration is not known in advance.
Syntax
The syntax of while loop is as follows:
while (condition)
statement;
Condition
The condition is given as a relational expression. The statement is executed only if the given condition is true. If the condition is false, the statements are never executed.
Statement
The statement is the instruction that is executed when the condition is true. If two or more statements are used, these are given in braces It is called the body of the loop.
The syntax for compound statements is as follows:
while (condition)
{
statement 1;
statement 2;
.
.
statement N;
}
Working of ‘while’ Loop
In C++ the loops, First of all, the condition is evaluated. If it is true, the control enters the body of the loop and executes all statements in the body. After executing the statement, it again moves to the start of the loop and evaluates the condition again. This process continues as long as the conditions remain true. When the conditions become false, the loop is terminated. while the loop terminates only when the condition becomes false. If the conditions remain true, the loop never ends. A loop that has no endpoints are known as an infinite loop.
Flowchart
The flowchart of while loop is as follows:
Program
Write a program that displays “Zitoc.com” four times using a while loop.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
z=1;
while(n<=4)
{
cout<<”Zitoc.com”;
z++;
}
getch();
}
Output:
Zitoc.com
Zitoc.com
Zitoc.com
Zitoc.com
How above Program Works?
The above program uses a variable n to control the iterations of the loop. It is known as a counter variable. The variable n. is initialized to 1. When the condition Ls evaluated for the first time, the value of n is less than 5 so the condition is true. The control enters the body of the loop. The body of the loop contains two statements. The first statement prints Pakistan on the screen. The second statement increments the value of n by 1 and makes it 2. The control moves back to the condition after executing both statements. This process continues for five times. When the value of n becomes 6, the condition becomes false and the loop terminates.
Program
Write a program that displays counting from 1 to 10 using a while loop.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
n=1;
while(n<=10)
{
cout<<”n”<<endl;
z++;
}
getch();
}
Output:
1
2
3
4
5
6
7
8
9
10
‘do while’ Loop
do-while is an iterative control in the C++ language. This Loop in C++ executes one or more statements while the given condition is true. In this loop, the condition comes after the body of the loop. It is an important loop in a situation when the loop body must be executing at least once.
Syntax
The syntax of while loop is as following:
do
{
statement 1:
statement 2:
.
.
.
statement
} while (condition);
do
It is the keyword that indicates the beginning of the loop.
Condition
The condition is given as a relational expression. The statement is executed only if the given conditions are true. If the condition is false, the statements are never executed.
Statement
statements are written in braces {}. It is called the body of the loop.
Working of ‘do-while’ loop
First of all, the body of the loop is executed. After executed the statements ion loop body, the condition is evaluated. If is true, the control again enters the body of the loop and executes all statements in the body again. This process continues as long as the condition remains true. The loop terminates when the condition becomes false. This loop is executed at least once even if the condition is false in the beginning.
Flowchart
Difference between ‘while’ and do ‘while’ Loop
The difference between ‘while’ and ‘do-while’ Loop
while loop | ‘do-while’ Loop |
In the while loop, the condition comes before the body of the loop. | In the do-while loop, the condition comes after the body of the loop. |
If the condition is false in the beginning, while the loop is never executed. | do-while executed at least once even if the condition is false in the beginning. |
Program:
Write a program that displays back-counting from 10 to 1 using a do-while loop.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
z=10;
do
{
cout<<”z”<<endl;
z = z-1;
} while(z>=1);
getch();
}
Output:
10
9
8
7
6
5
4
3
2
1
How above Program Works?
The above program does not proceed until the user enters a valid input of d or w The program repeatedly shows a message to the user to enter a salad input The condition indicates that the loop continues if the user enters. a value other than w and d.
Pretest and Posttest in Loops
A pretest is a condition that as used to test for the completion of the loop at the top of the loop. In this type of loop, the statements inside the loop body can newer execute if the terminating condition is false the first lime it is tested.
Example
Following is an example of pretest condition The statements in the body of the loop cannot be executed if the condition is false.
n = 0;
while(n = = 0)
{
loop body
}
A posttest is a condition that 1 used to test for the completion of the loop at the bottom tit loop. It means that the statements in the loop will always be executed at least once.
Example
Following is an example of a posttest condition. The statement in the body of the loop will be executed at least once even if the condition is false.
do
{
loop body
} while(z= =0);
‘for’ Loop
for loop execute one or more states for a specified number of times. Thus loop 6 also called a counter-controlled loop. It is the most flexible Loop in C++ That is why it is the most frequently-used loop by the programmers.
Syntax
The syntax of for hop is as follows
for (initialization; condition; Increment/decrement)
{
statement 1:
statement 2:
statement N:
}
Initialization
It specifies the starting value of a counter variable. One or man, variables can be initialized in this part. To initialize many variables, each ramble is separated by the comma.
Condition
The condition is given as a relational expression. The statement is executed only if the given conditions are true. If the condition is false, the statement is never executed.
Increment/decrement
This part of the loop specifies the change in the counter variable, each variable must be separated by the comma.
Statement
The statement is the instruction that is executed when the condition is true. If two or more statements are used, these are given in braces {}. It is called the body of the loop.
Working ‘for’ loop
The number of iterations depends on the initialization, condition and increment/decrement parts. The initialization part of executed only once when control enters the loop. After initialization, the giving condition is evaluated. If it is true, the control enters the body of the loop and executes all statements in it. Then the increment/decrement part executes that changes the value of the counter variable. The control again moves to the condition part. This process continues while the condition remains true. The loop of terminated when the condition remains true. The loop is terminated when the condition becomes false.
Flowchart:
Program:
Write a program that displays from 1 to 5 using for loop.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int z;
for(z = 1; z<=5; z++)
cout<<z<<endl;
getch();
}
Output:
1
2
3
4
5
Program
Write a program that finds the sum of squares of integers from 1 to n. where n is a positive value entered by the user (i.e. Sum 12 + 22 + 32 +……….+ n2).
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int n,c;
long int sum;
sum = 0;
cout<<”Enter the number”;
cin>>n;
for(c =1; c<=n; c++)
sum = sum + (c * c);
cout<<”Sum is: ”<<sum;
getch();
}
Output:
Enter a number: 5
The sum is: 55
Explanation
The abase program declares three variables c, in and sum. It inputs a positive number from the user and stores this number in the variable n. In the initialization part of the loop, c is initialized to I. The condition statement c<=n uses n that is entered by the user. The loop will execute n times. The increment part increments the counter variable by 1.
In each iteration, the statement sum = sum + (c * c) is executed. It takes the of the counter variable c and adds it to the variable sum. The loop runs n times and the squares of numbers from 1to n are summed up. After completing for loop the court statement s executed that displays the sum of the squares of number from 1 to n.
Nested Loops
A loop within a loop is called a nested loop. In nested loops, the inner loop is executed completely with each change in the value of the counter variable of the outer loop.
The nesting can be done up to any level. The increase in the level of nesting increases the complexity of the nested loop. Any loop can be used as an inner loop of another loop. For example,
while loop can be used as an outer loop and for loop can be used as an inner loop in the nested loop.
Explanation
The above example uses nested for loop. The outer loop executes two times and the inner loop executes three times with each iteration of the outer loop. It means that the inner loop executes six times in total. When the value of i is 1 in the first iteration of the outer loop, the value of j changes from 1 to 3 in three iterations of the inner loop. Similarly, when the value of i is 2 in
the second iteration of the outer loop, the value of j again changes from 1 to 3 in three iterations of
the inner loop.
Example
The following program explains the use of nested while loops.
#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int i,j;
i = 0;
while(i<=2)
{
j=1; while(j<=3)
{
cout<<”outer”<<i<<”inner:”<<j<<endl;
j++;
}
}
i++;
}
Output:
outer: 1 inner: 1
outer: 1 inner: 2
outer: 1 inner: 3
outer: 2 inner: 1
outer: 2 inner: 2
outer: 2 inne : 3