6 - Iteration Statements

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Iteration Statements

Introduction

● Normally, when a statement is written in c++ it is executed only once. But


what if we want to repeat a statement multiple times, for example showing a
message 10 times.
● In that case, writing output statement 10 times will be difficult and time
consuming. For this, loops in programming come into use when we need to
repeatedly execute a block of statements.
● An iteration statement allows a program to repeat an action while some
condition remains true.
C++ program to illustrate need of loops
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
Loops

In computer programming, a loop is a sequence of instructions that is repeated


until a certain condition is reached.

● An operation(s) is done, such as getting an input from user or performing


some operations, and then some condition is checked such as whether a
counter has reached a prescribed number.
● Counter not Reached: If the counter has not reached the desired number, the
compiler returns to the first instruction in the sequence and repeat it.
● Counter reached: If the condition has been reached, the compiler exits the
loop and executes the instruction outside the loop.
Loops

● There are mainly two types of loops:

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

● Initialization Expression: In this expression we have to initialize the loop


counter to some value. For example: int i=1; This statement is executed only
once.

● 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;

● Update Expression: After executing loop body this expression


increments/decrements the loop variable by some value. for example: i++;
After updating the value of initialized variables and compiler will again check
the condition.
Pseudo code to demonstrate the use of loop

If counter is less than or equal to 10


Show the message “Hello World”
Increase the value of counter by 1

● 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()
{

for (int i = 1; i <= 10; i++)


{
printf( "Hello World\n");
}

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

#include <iostream> OUTPUT


using namespace std;
int main() { Enter a positive integer: 29
int i, n;
bool isPrime = true; 29 is a prime number.
cout << "Enter a positive integer: ";
cin >> n;
if (n == 0 || n == 1)
isPrime = false; // 0 and 1 are not prime numbers
else {
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime)
cout << n << " is a prime number";
else
cout << n << " is not a prime number";

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”

This loop will print Hello World infinitely.


Optional Expressions in a for Statement

● 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 loop is used to iterate a part of the program several times.

● 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

● A while loop evaluates the condition


● If the condition evaluates to true, the code inside the while loop is executed.
● The condition is evaluated again.
● This process continues until the condition is false.
● When the condition evaluates to false, the loop terminates.
Write a program that uses while loop to print hello world 6 times
#include <iostream>
using namespace std;
OUTPUT
int main() {
int i = 1; Hello World
while (i < 6)
Hello World
{
cout << "Hello World\n"; Hello World
i++;
Hello World
}
return 0; Hello World
}
Hello World
Write a program to find the sum of positive numbers only if the user
enters a negative number, the loop ends.
#include <iostream>
OUTPUT
using namespace std;
int main() { Enter a number: 6
int number;
Enter a number: 12
int sum = 0;
cout << "Enter a number: "; Enter a number: 7
cin >> number;
Enter a number: 0
while (number >= 0) {
sum =sum+ number; Enter a number: -2
cout << "Enter a number: ";
cin >> number;
} The sum is 25
cout << "\nThe sum is " << sum << endl;
return 0;
}
Write a program in C++ to display the n terms of harmonic series and
their sum: 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms
#include <iostream>
using namespace std;
int main(){
int i=1, n;
float s = 0.0;
cout << "\n\n Display n terms of harmonic series and their sum:\n";
cout << " The harmonic series: 1 + 1/2 + 1/3 + 1/4 + 1/5 ... 1/n terms\n";
cout << "-----------------------------------------------------------------\n";
cout << " Input number of terms: ";
cin >> n;
while (i <= n)
{
if (i < n)
OUTPUT

Display n terms of harmonic


{
cout << "1/" << i << " + "; series and their sum:
s += 1 / (float)i;
}
if (i == n) The harmonic series: 1 + 1/2 +
{ 1/3 + 1/4 + 1/5 ... 1/n terms
cout << "1/" << i;
s += 1 / (float)i;
} --------------------------------------
i++;
} ---------------------------
cout << "\n The sum of the series upto " << n << " terms: " << s << endl;
Input number of terms: 5
}

1/1 + 1/2 + 1/3 + 1/4 + 1/5


Write a program in C++ to find the sum of digits of a given number.

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

Find the sum of the series 1 +


1/2^2 + 1/3^3 +.....+ 1/n^n:
--------------------------------------
while ( i <= n) --------------------------
{ Input the value for nth term: 5
a = 1 / pow(i, i); 1/1^1 = 1
cout << "1/" << i << "^" << i << " = " << a << endl; 1/2^2 = 0.25
sum += a; 1/3^3 = 0.037037
i++; 1/4^4 = 0.00390625
} 1/5^5 = 0.00032
cout << " The sum of the above series is: " << sum << endl; The sum of the above series is:
} 1.29126
Write a program in C++ that ask user if they want to continue or not. If
the user presses y the program should keep asking to enter a number.
At the end display how many positive, negative and zero’s were entered.

#include <iostream> OUTPUT


using namespace std;
int main(){ Input the number of terms : 5
int pCount=0, nCount=0, zCount=0, num;
char ch;
Number is : 1 and the cube of 1 is: 1
cout<<"Enter y if you want to continue:";
cin>>ch;
while(ch=='y' || ch=='Y') Number is : 2 and the cube of 2 is: 8
{
cout<<"Enter a number:";
cin>>num; Number is : 3 and the cube of 3 is: 27
if(num>0)
pCount++;
Number is : 4 and the cube of 4 is: 64
else if (num<0)
nCount++;
else if (num==0)
zCount++;
else
cout<<"Not a number";
cout<<"Enter y if you want to continue:";
cin>>ch;
}
cout<<endl<<"No of positive numbers entered:"<<pCount<<endl;
cout<<"No of negative numbers entered:"<<nCount<<endl;
cout<<"No of zero entered:"<<zCount;
}
Do-While Loop

● The do/while loop is a variant of the while loop.

● 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

float avg=0.0; Enter q to quit or any other key to continue: f

int marks, counter=0, sum=0; Enter Marks in Quiz:67

char ch; Enter q to quit or any other key to continue: n

do{ Enter Marks in Quiz:87


Enter q to quit or any other key to continue: q
cout<<"Enter Marks in Quiz:";
cin>>marks; Average of students on quiz is:62.6667

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.

#include <iostream> OUTPUT


using namespace std;
int main() { Enter your pin to login:5678
int pin=5421,pin_check;
Enter your pin to login:9021
do
{ Enter your pin to login:1234
cout<<"Enter your pin to login:"; Enter your pin to login:5467
cin>>pin_check;
Enter your pin to login:5421
} while(pin_check!=pin);
cout<<"Account Logged in successfully."; Account Logged in
return 0; successfully.
}
Modify Program such that if the pin does not match the default pin then display Invalid Pin.

#include <iostream> OUTPUT


using namespace std;
int main() { Enter your pin to login:3457
int pin=5421,pin_check,attempts=0;
Invalid Pin
do{
cout<<"Enter your pin to login:"; Enter your pin to login:5412
cin>>pin_check; Invalid Pin
if(pin!=pin_check){
Enter your pin to login:5421
cout<<"Invalid Pin"<<endl;
} Account Logged in
} while(pin_check!=pin); successfully.
cout<<"Account Logged in successfully.";
}
Modify Program such that maximum 3 attempts to re-enter pin are allowed. After 3 tries the account
should get locked.

#include <iostream> OUTPUT


using namespace std;
int main() { Enter your pin to login:7890
int pin=5421,pin_check,attempts=0;
Invalid Pin
do{
cout<<"Enter your pin to login:"; Enter your pin to login:3256
cin>>pin_check; Invalid Pin
if(pin!=pin_check){
Enter your pin to login:3451
cout<<"Invalid Pin"<<endl;
attempts++; Invalid Pin
} Account Locked
} while(pin_check!=pin && attempts<3);
if(attempts==3)
cout<<"Account Locked";
if(attempts==3)
cout<<"Account Locked";
else
cout<<"Account Logged in sucessfully.";
}
C++ Program to Find LCM

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

A loop within another loop is called a nested loop.


C++ program to display 7 days of 3 weeks
#include <iostream>
OUTPUT
using namespace std;
int main() {
int weeks = 3, days_in_week = 7; Week: 1
for (int i = 1; i <= weeks; ++i) { Day:1
cout << "Week: " << i << endl; Day:2
for (int j = 1; j <= days_in_week; ++j) {
cout << " Day:" << j << endl; …
} Week: 2
} Day:1
return 0;
Day:2
}

Pattern 1
#include <iostream>
OUTPUT
using namespace std;
int main() {
for (int i = 1; i <= 5; ++i) { *
for (int j = 1; j <= i; ++j) * *
{ * * *
cout << "* ";
} * * * *
cout << endl; * * * * *
}
return 0;
}
Pattern 2 Pattern 4
1 1
12
123 22
1234
12345 333

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

You might also like