Professional Documents
Culture Documents
6 - Iteration Statements
6 - Iteration Statements
6 - Iteration Statements
Introduction
1. Entry Controlled loops: In this type of loops the test condition is tested
before entering the loop body. For Loop and While Loop are entry
controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested
or evaluated at the end of loop body. Therefore, the loop body will
execute atleast once, irrespective of whether the test condition is true or
false. do – while loop is exit controlled loop.
For Loop
● A for loop is a repetition control structure which allows to write a loop that
is executed a specific number of times.
● Syntax:
for(initialization; condition; update){
//code to be executed
}
In for loop, a loop variable is used to control the loop. First initialize this loop
variable to some value, then check whether this variable is less than or greater
than counter value. If statement is true, then loop body is executed and loop
variable gets updated . Steps are repeated till exit condition comes.
For Loop
● Test Expression: In this expression the compiler will test the condition. If the
condition evaluates to true then compiler will execute the body of loop
otherwise compiler will exit from the for loop. For example: i <= 10;
● In Loop, the statement needs to be written only once and the loop will be
executed 10 times as shown above.
Code to demonstrate the use of loop
#include <iostream>
using namespace std;
int main()
{
return 0;
}
A class of ten students took a quiz. The grades (integers in the range 0–
100) for this quiz are available to you. Write a program to determine
the class average on the quiz.
Pseudo Code:
Set total to zero
Set grade counter to one
If grade counter is less than or equal to ten
Prompt the user to enter the next grade
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
#include <iostream> OUTPUT
using namespace std;
Enter Grade in Quiz:45
int main () {
Enter Grade in Quiz:54
int total=0;
Enter Grade in Quiz:88
float avg=0.0;
Enter Grade in Quiz:74
int grade;
Enter Grade in Quiz:35
for(int i=1; i<=10; i++)
Enter Grade in Quiz:84
{
Enter Grade in Quiz:63
cout<<"Enter Grade in Quiz:";
cin>>grade;
OUTPUT
total=total+grade;
} Enter Grade in Quiz:25
avg=total/10.0; Enter Grade in Quiz:41
cout<<"Average of students on quiz is:"<<avg; Enter Grade in Quiz:75
} Average of students on quiz
is:58.4
OUTPUT
C++ Program to Generate
Multiplication Table Enter a positive integer: 5
5*1=5
#include <iostream>
5 * 2 = 10
using namespace std; 5 * 3 = 15
int main() { 5 * 4 = 20
int n; 5 * 5 = 25
cout << "Enter a positive integer: "; 5 * 6 = 30
cin >> n; 5 * 7 = 35
for (int i = 1; i <= 10; ++i) { 5 * 8 = 40
cout << n << " * " << i << " = " << n * i << endl; 5 * 9 = 45
} 5 * 10 = 50
C++ Program to Check Whether a Number is Prime or Not
return 0;
}
Find Factorial of a given number
#include <iostream>
using namespace std; OUTPUT
int main() {
int n; Enter a positive integer: 12
long double factorial = 1.0;
cout << "Enter a positive integer: "; Factorial of 12 = 479001600
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i)
factorial *= i;
cout << "Factorial of " << n << " = " << factorial;
}
return 0; }
Optional Expressions in a for Statement
● All three expressions in the head of the for loop are optional.
● If you omit all 3 expressions from for loop it becomes an infinite loop
for( ; ; )
cout<<”Hello World”
● Similarly you can initialize the counter variable before for loop and update
expression can be placed inside the for loop body.
int i=1;
for(;i<=10;)
{
\\some statements;
i++;
}
While Loop
● While loops are used in situations where we do not know the exact number
of iterations of loop beforehand. The loop execution is terminated on the
basis of test condition.
While Loop
Syntax:
initialization expression;
while (condition)
{
// statements
update_expression;
}
While Loop
OUTPUT
#include <iostream>
using namespace std; Find the sum of digits of a
int main(){ given number:
int num1, num2, r, sum=0; --------------------------------------
cout << "\n\n Find the sum of digits of a given number:\n"; --------
cout << "----------------------------------------------\n"; Input a number: 9834
cout << " Input a number: "; The sum of digits of 9834 is:
cin >> num1; 24
num2 = num1;
while (num1 > 0)
{
r = num1 % 10;
num1 = num1 / 10;
sum = sum + r;
}
cout << " The sum of digits of " << num2 << " is: " << sum << endl;
}
Write a program in C++ to find the sum
of the series
1 + 1/2^2 + 1/3^3 + …..+ 1/n^n
#include <iostream>
#include <math.h>
using namespace std;
int main(){
double sum = 0, a;
int n, i;
cout << "\n\n Find the sum of the series 1 + 1/2^2 + 1/3^3 +.....+ 1/n^n:\n";
cout << "----------------------------------------------------------------\n";
cout << " Input the value for nth term: ";
cin >> n;
OUTPUT
● This loop will execute the code block once, before checking if the condition
is true, then it will repeat the loop as long as the condition is true.
Do-While Loop
Syntax:
do {
// code block to be executed
}
while (condition);
Display Numbers from 1 to 5 using do-while loop.
OUTPUT
#include <iostream>
using namespace std; 12345
int main() {
int i = 1;
do {
cout << i << " ";
++i;
} while (i <= 5);
return 0;
}
A class of some students took a quiz. Write a program that ask user to
input number in quiz repeatedly until q is pressed. If q is pressed the
loop should end and determine the class average on the quiz.
#include <iostream> OUTPUT
using namespace std;
int main () { Enter Marks in Quiz:34
sum=sum+marks;
counter++;
cout<<"Enter q to quit or any other key to continue: ";
cin>>ch;
} while(ch!='q' && ch!='Q');
avg=sum/counter;
cout<<"Average of students on quiz is:"<<avg;
}
A program that ask user to input pin until the user enter correct pin.
OUTPUT
LCM (Lowest Common Multiple) of two integers a and b
is the smallest positive integer that is divisible by both a and b. Enter a number: 6
Enter a number: 12
#include <iostream> Enter a number: 7
using namespace std; Enter a number: 0
int main() Enter a number: -2
{
int n1, n2, max; The sum is 25
cout << "Enter two numbers: ";
cin >> n1 >> n2;
// maximum value between n1 and n2 is stored in max
max = (n1 > n2) ? n1 : n2;
do {
if (max % n1 == 0 && max % n2 == 0) {
cout << "LCM = " << max;
break;
}
else
++max;
} while (true);
return 0;
}
Nested Loop Structure
Pattern 3 4444
1 55555
23 Pattern 5
456 ****
****
Write a program in C++ to find the frequency of each digit in a given
integer.
#include <iostream> OUTPUT
using namespace std;
int main() Input any number: 5512924
{
The frequency of 0 = 0
int n, i, j, ctr, r;
cout << "Input any number: "; The frequency of 1 = 1
cin >> n; The frequency of 2 = 2
for (i = 0; i < 10; i++) The frequency of 3 = 0
{
cout << "The frequency of " << i << " = "; The frequency of 4 = 1
ctr = 0; The frequency of 5 = 2
for (j = n; j > 0; j = j / 10) The frequency of 6 = 0
{
r = j % 10; OUTPUT
if (r == i)
{ The frequency of 7 = 0
ctr++;
The frequency of 8 = 0
}
} The frequency of 9 = 1
cout << ctr << endl;
}
}
Write a program in C++ to calculate the series (1) + (1+2) + (1+2+3) +
(1+2+3+4) + ... + (1+2+3+4+...+n).
#include <iostream> OUTPUT
using namespace std;
int main() Input the value for nth term: 4
{
1=1
int i, j, n, sum = 0, tsum;
cout << " Input the value for nth term: "; 1+2 = 3
cin >> n; 1+2+3 = 6
for (i = 1; i <= n; i++) 1+2+3+4 = 10
{
tsum = 0; The sum of the above series is: 20
for (j = 1; j <= i; j++)
{
sum += j;
tsum += j;
cout << j;
if (j < i)
{
cout << "+";
}
}
cout << " = " << tsum << endl;
}
cout << " The sum of the above series is: " << sum << endl;
}
Write a program in C++ to find prime number within a range.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num1,num2;
int total=0,ctr=0;
cout << " Input number for starting range: ";
cin>> num1;
cout << " Input number for ending range: ";
cin>> num2;
cout << "\n The prime numbers between "<<num1<<" and "<<num2<<"
are:"<<endl;
for(int i=num1;i<=num2;i++)
{
OUTPUT
for(int j=2;j<=i/2;j++)
Input number for starting range: 1
{
if(i%j==0) Input number for ending range: 10
{
ctr++;
The prime numbers between 1 and 10 are:
break;
} 2357
}
if(ctr==0 && i!=1) The total number of prime numbers between 1 to 10 is:
{
4
total++;
cout<<i<<" ";
}
ctr=0;
}
cout<<"\n\n The total number of prime numbers between "<<num1<<" to
"<<num2<<" is: "<<total<<endl;
return 0;
}
Break Statement
The break statement is used to terminate the execution of the current loop.
Whenever there is a need to end the loop, you need to add the break statement.
Once the break statement is met, all the iterations are stopped, and the control is
shifted outside the loop.
Continue Statement
The continue statement is used to move to the next iteration, it is also used for
termination, but unlike break, it is not used to terminate the entire execution of
the loop but only the current iteration of the loop.
Program to find the sum of positive numbers, If the user enters a negative
numbers, the loop should end. If the user enters a number greater than 50,
it should not be added in sum.
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
cout << "Enter a number: ";
cin >> number;
if (number < 0) {
cout<<"Breaking Loop."<<endl;
break;
OUTPUT
Enter a number: 78
Number skipped.
} Enter a number: 12
if (number > 50) Enter a number: 34
{
Enter a number: 23
cout<<"Number skipped."<<endl;
continue; Enter a number: 45
} Enter a number: 65
sum += number;
Number skipped.
}
cout << "The sum is " << sum << endl; Enter a number: -90
return 0; Breaking Loop.
}
The sum is 114