0% found this document useful (0 votes)
14 views

LOOPS IN C++

Uploaded by

mayankchitra3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

LOOPS IN C++

Uploaded by

mayankchitra3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Loops in C++

Loops in programming come into use when we need to repeatedly execute a block of
statements. For example: Suppose we want to print “Hello World” 10 times. This can
be done in two ways as shown below:
Iterative Method
An iterative method to do this is to write the cout statement 10 times.

C++

// C++ program to illustrate need of loops


#include <iostream.h>

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;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Using Loops

In Loop, the statement needs to be written only once and the loop will be executed 10
times as shown below.
In computer programming, a loop is a sequence of instructions that is repeated until a
certain condition is reached.

Initialization , condition checking, increment/decrement


• An operation is done, such as getting an item of data and changing it, 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 next
instruction in the sequence returns to the first instruction in the sequence and
repeat it.
• Counter reached: If the condition has been reached, the next instruction “falls
through” to the next sequential instruction or branches outside the loop.

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 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
}
In for loop, a loop/counter 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.
• Initialization Expression: In this expression we have to initialize the loop counter
to some value. for example: int i=1;
• Test Expression: In this expression we have to test the condition. If the condition
evaluates to true then we will execute the body of loop and go to update
expression otherwise we 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++;
• Increment/ decrement operator ++, --
i++ i=i+1
i-- i=i-1

Equivalent flow diagram for loop :


Example:

C++

// C++ program to illustrate for loop


#include <iostream.h>

int main()
{
int i=0;

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


{
cout<< "Hello World\n";
}

return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World

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. Do…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.
Syntax:
We have already stated that a loop is mainly consisted of three statements –
initialization expression, test expression, update expression. The syntax of the three
loops – For, while and do while mainly differs on the placement of these three
statements.

initialization expression; int i=1;

while (test_expression) while(i<=10)


{ {cout<<”i=”<<i<<endl;
i++;
}
// statements

update_expression;
}

Flow Diagram:
Example:

C++

// C ++program to illustrate while loop


#include <iostream.h>

int main()
{
// initialization expression
int i = 1;

// test expression
while (i < 6)
{
cout<< "Hello World\n";

// update expression
i++;
}

return 0;
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World

do while loop
In do while loops also the loop execution is terminated on the basis of test condition.
The main difference between do while loop and while loop is in do while loop the
condition is tested at the end of loop body, i.e do while loop is exit controlled whereas
the other two loops are entry controlled loops.
Note: In do while loop the loop body will execute at least once irrespective of test
condition.

Syntax:
initialization expression;
do
{
// statements

update_expression;
} while (test_expression);
Note: Notice the semi – colon(“;”) in the end of loop.

Flow Diagram:

Example:

C++

// C ++program to illustrate do-while loop


#include <iostream.h>

int main()
{
int i = 2; // Initialization expression
do
{
// loop body
cout<< "Hello World\n";

// update expression
i++;

} while (i < 1); // test expression

return 0;
}
Output:
Hello World
In the above program the test condition (i<1) evaluates to false. But still as the loop is
exit – controlled the loop body will execute once.
What about an Infinite Loop?
An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a
functional exit so that it repeats indefinitely. An infinite loop occurs when a condition
always evaluates to true. Usually, this is an error.

// C+_ program to demonstrate infinite loops


// using for and while
// Uncomment the sections to see the output

#include <iostream.h>

int main ()
{
int i;

// This is an infinite for loop as the condition


// expression is blank
for ( ; ; ) for( ; i<=10 ;)
{
cout<<”This loop will run forever.\n";
}

// This is an infinite for loop as the condition


// given in while loop will keep repeating infinitely
/*
while (i != 0)
{
i-- ;
cout<< "This loop will run forever.\n";
}
*/

// This is an infinite for loop as the condition


// given in while loop is "true"
/*
while (true)
{
cout<< "This loop will run forever.\n";
}
*/
}

Output:
This loop will run forever.
This loop will run forever.
...................
More Advanced Looping Techniques
• Range-based for loop in C++
• for_each loop in C++
Important Points:
• Use for loop when number of iterations is known beforehand, i.e. the number of
times the loop body is needed to be executed is known.
• Use while loops where exact number of iterations is not known but the loop
termination condition is known.
• Use do while loop if the code needs to be executed at least once like in Menu
driven programs

FOR LOOP PROGRAMS

1. Write A Program To Find Square Root Of Numbers

#include<iostream.h>
#include<conio.h>
#include<math.h>

int main()
{
int i;
clrscr();
for(i=10;i<=100;i++)
{
cout<<” Number” <<i<<”\t\t Squareroot=”<<sqrt(i)<<endl;

}
cout<<’’\n Program completed”;
return 0;
getch();
}

OUTPUT

Number 10 Squareroot=3.16
Number 11 Squareroot=4
Number 12 Squareroot=4.1
.
.
.
Number 100 Squareroot=10

Program completed

Example of inbuilt functions in math.h


pow(x,5)
pow(5,5)=5*5*5*5*5
sqrt(x)
cos()

2. Write a program in C++ to find the first 10 natural numbers.


Pictorial Presentation:

Sample Solution :-

C++ Code :
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "\n\n Find the first 10 natural numbers:\n";
cout << "---------------------------------------\n";
cout << " The natural numbers are: \n";
for (i = 1; i <= 10; i++)
{
cout << i << " ";
}
cout << endl;
}

Sample Output:
Find the first 10 natural numbers:
---------------------------------------
The natural numbers are:
1 2 3 4 5 6 7 8 9 10
Flowchart:
3. Write a program in C++ to find the perfect numbers between 1 and 500.
Pictorial Presentation:

Sample Solution :-
C++ Code :
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Find the perfect numbers between 1 and 500:\n";
cout << "------------------------------------------------\n";
int i = 1, u = 1, sum = 0;
cout << "\n The perfect numbers between 1 to 500 are: \n";
while (i <= 500)
{
while (u <= 500)
{
if (u < i)
{
if (i % u = = 0)
sum = sum + u;
}
u++;
}
if (sum = = i) {
cout << i << " " << "\n";
}
i++;
u = 1;
sum = 0;
}
}

Sample Output:
Find the perfect numbers between 1 and 500:
------------------------------------------------

The perfect numbers between 1 to 500 are:


6
28
496

Flowchart:
4. Write a program in C++ to check whether a number is prime or not.
Pictorial Presentation:

Sample Solution :-
C++ Code :
#include <iostream>
using namespace std;
int main()
{
int num1, ctr = 0;
cout << "\n\n Check whether a number is prime or not:\n";
cout << "--------------------------------------------\n";
cout << " Input a number to check prime or not: ";
cin>> num1;
for (int a = 1; a <= num1; a++)
{
if (num1 % a == 0)
{
ctr++;
}
}
if (ctr == 2)
{
cout << " The entered number is a prime number. \n";
}
else {
cout << " The number you entered is not a prime number. \n";
}
}

Sample Output:
Check whether a number is prime or not:
--------------------------------------------
Input a number to check prime or not: 13
The entered number is a prime number.
Flowchart:
5. Write a program in C++ to find the sum of digits of a given number.
Pictorial Presentation:

Sample Solution :-
C++ Code :
#include <iostream>
using namespace std;
int main()
{
int num1, num2, r, sum=0;
cout << "\n\n Find the sum of digits of a given number:\n";
cout << "----------------------------------------------\n";
cout << " Input a number: ";
cin >> num1; 1234
num2 = num1; 1234
while (num1 > 0)
{
r = num1 % 10; 1234%10 r=4 123%10=3 12%10=2 1
num1 = num1 / 10; 1234/10=123 123/10=12 12/10=1
sum = sum + r; 0+4=4 4+3=7 7+2=9
9+1=10
}
cout << " The sum of digits of " << num2 << " is: " << sum << endl;
}

Sample Output:
Find the sum of digits of a given number:
----------------------------------------------
Input a number: 1234
The sum of digits of 1234 is: 10

Flowchart:
6. Write a program in C++ to find the factorial of a number.
Pictorial Presentation:

Sample Solution :-
C++ Code :
#include <iostream>
using namespace std;
int main()
{
int num1,factorial=1;
cout << "\n\n Find the factorial of a number:\n";
cout << "------------------------------------\n";
cout << " Input a number to find the factorial: ";
cin>> num1;
for(int a=1;a<=num1; a++)
{
factorial=factorial*a; 1*1, 1*2, 2*3,6*4,24*5
}
cout<<" The factorial of the given number is: "<<num1<<factorial<<endl;
return 0;
}
Sample Output:
Find the factorial of a number:
------------------------------------
Input a number to find the factorial: 5
The factorial of the given number is: 120
Flowchart:
7. Write a program in C++ to display the pattern like right angle triangle using an
asterisk.
Pictorial Presentation:

C++ Code :
#include <iostream>
using namespace std;

int main()
{
int i,j,rows;
cout << "\n\n display the pattern like right angle triangle using an asterisk:\n";
cout << "---------------------------------------------------------------------\n";
cout << " Input number of rows: ";
cin >> rows;
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
{cout<<"*";}
cout<<endl;
}
}
Sample Output:
display the pattern like right angle triangle using an asterisk:
---------------------------------------------------------------------
Input number of rows: 5
* 1
** 12
*** 12 3
**** 12 3 4
*****
Flowchart:
8. Write a program in C++ to make such a pattern like right angle triangle with
number increased by 1.
Pictorial Presentation:
Sample Solution:-
C++ Code :
#include <iostream>
#include <string>
using namespace std;

int main()
{
int i,j,rows, k=1;
cout << "\n\n Display such a pattern like right angle triangle with number increased
by 1:\n";
cout << "---------------------------------------------------------------------------------\n";
cout << " Input number of rows: ";
cin >> rows;
for(i=1;i<=rows;i++)
{
for(j=1; j<=i; j++)
{cout<<k++<<" ";}
cout<<endl;
}
}

Sample Output:
Display such a pattern like right angle triangle with number increased by 1:
---------------------------------------------------------------------------------
Input number of rows: 4
1
23
456
7 8 9 10
Flowchart:
9. Write a program in C++ to display the sum of the series [ 1+x+x^2/2!+x^3/3!+....].
Sample Solution:-
C++ Code :
#include <iostream>
using namespace std;

int main()
{
float x, sum, no_row;
int i, n;
cout << "\n\n Display the sum of the series [ 1+x+x^2/2!+x^3/3!+....]\n";
cout << "------------------------------------------------------------\n";
cout << " Input the value of x: ";
cin >> x;
cout << " Input number of terms: ";
cin >> n;
sum = 1;
no_row = 1;
for (i = 1; i < n; i++)
{
no_row = no_row * x / (float)i;
sum = sum + no_row;
}
cout << " The sum is : " << sum << endl;
}

Sample Output:
Display the sum of the series [ 1+x+x^2/2!+x^3/3!+....]
------------------------------------------------------------
Input the value of x: 3
Input number of terms: 5
The sum is : 16.375

Flowchart:
C++ while Loop
The syntax of the while loop is:
while (condition) {
// body of the loop
}
Here,
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.
To learn more about the conditions, visit C++ Relational and Logical Operators.

Flowchart of while Loop


Flowchart of C++ while loop

Example 1: Display Numbers from 1 to 5


// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main()
{
int i = 1;

// while loop from 1 to 5


while (i <= 5)
{
cout << i << " ";
++i;
}

return 0;
}
Output
12345
Here is how the program works.

Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers // if the user enters a negative number,
the loop ends // the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main()
{
int number;
int sum = 0; // take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0)
{ // add all positive numbers
sum =sum+ number; // take input again if the number is positive
cout << "Enter a number: ";
cin >> number; // display the sum
cout << "\nThe sum is " << sum << endl; }
return 0;
}

Output

Enter a number: 6
Sum=6
Enter a number: 12
Sum=18
Enter a number: 7
Sum=25
Enter a number: 0
Sum=25
Enter a number: -2
The sum is 25

In this program, the user is prompted to enter a number, which is stored in the
variable number.
In order to store the sum of the numbers, we declare a variable sum and initialize it to
the value of 0.
The while loop continues until the user enters a negative number. During each
iteration, the number entered by the user is added to the sum variable.
When the user enters a negative number, the loop terminates. Finally, the total sum is
displayed.

DO…WHILE LOOP
The do...while loop is a variant of the while loop with one important difference: the
body of do...while loop is executed once before the condition is checked.
Its syntax is:
do
{
// body of loop;
}
while (condition);
Here,
The body of the loop is executed at first. Then the condition is evaluated.
If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
The condition is evaluated once again.
If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
This process continues until the condition evaluates to false. Then the loop stops.

Flowchart of do...while Loop

Flowchart of C++ do...while loop

Example 3: Display Numbers from 1 to 5


// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
int i = 1;

// do...while loop from 1 to 5


do {
cout << i << " ";
++i;
}
while (i <= 5);

return 0;
getch();
}
Output
12345

#include<iostream.h>
#include<conio.h>
void main()
{
float i;
cout<<”enter the value of i”<<endl; enter the value of i
cin>>i; 3.14532
cout.precision(2);
cout<<”\nthe number is=”<<i; the number is=3.14
getch();
}

#include<iostream.h>
#include<conio.h>
void main()
{
cout<<”HELLO”; HELLO***** My Name is----- AMIT
cout.fill(“*”);
cout.width(5);
cout<<”My Name is”;
cout.fill(“_”);
cout.width(5);
cout<<”AMIT”;
getch();
}
Fibonacci series

Next term= sum of previous two terms


Fterm=0
Sterm=1
Tterm=1
Nterms=10
0 1 1 2 3 5 8 11 19 30

void main()
{
int Fterm=0, Sterm=1, Tterm, Nterms;
cout<<”enter the no. of terms”;
cin>> Nterms;
cout<<Fterm;
cout<<Sterm;
for(int 1=1; i<= Nterms;i++)
{ Tterm= Fterm+ Sterm;
cout<<Tterm;
Fterm= Sterm;
Sterm= Tterm;
}
getch();
}

You might also like