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

Unit 4 Loops in C++

Unit 4 covers loop control structures in C++, detailing the three main types: for, while, and do while loops. It explains their syntax, usage, and provides example programs for each type, demonstrating their functionality and output. Additionally, it introduces the break and continue statements, nested loops, and includes examples to illustrate their application.

Uploaded by

Roman Saadat
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)
4 views

Unit 4 Loops in C++

Unit 4 covers loop control structures in C++, detailing the three main types: for, while, and do while loops. It explains their syntax, usage, and provides example programs for each type, demonstrating their functionality and output. Additionally, it introduces the break and continue statements, nested loops, and includes examples to illustrate their application.

Uploaded by

Roman Saadat
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/ 12

UNIT 4 Loop Control Structure

Loop
Loops are very commonly used in programming. It allows to repeatedly execute one or more
statements in a program as many times as required. Loops provide an easy and efficient way
of writing computer programs.
There are three types of loops used in C++ programming. These are for, while and do while
loops.
1. The for Loop
The for loop is used to execute one or more statements repeatedly for a fixed number of
times.
It has the general form:
for (initialization; condition; increment/decrement)
{
Block of statements
}
In the initialization part, a variable (also known as loop variable) is assigned an initial value,
such as, k=1 or count=0. The condition is a relational expression such as k<=10. When loop is
executed, the condition is evaluated, if the condition is true, the block of statements within
the braces are executed otherwise it will exit the loop. After the execution of block of
statements, the control is transferred back to the increment/decrement part of the loop.
The loop variable is incremented or decremented using an assignment statement such as
k=k+1. The new value of loop variable is again checked with the condition. If the condition is
satisfied then the block of statements is again executed. In this manner, the loop is
repeatedly executed till the condition becomes false. If there is only one statement in the
loop then braces are not required. The initialization part is executed only once at the start of
loop.
//Program to print squares of the numbers from 1 to 10 on a single line.
#include <iostream>
using namespace std;
int main()
{ int j;
for (j=1; j<=10; j++)
{
cout << j*j <<”\t”;
}
cout <<endl;
return 0;
{

M. Sajjad Heder Pg.1


The output will be:
1 4 9 16 25 36 49 64 81 100

//Program to print the cubes of the numbers from 1 to 5, using


//a two-column format.
#include <iostream>
using namespace std;
int main()
{ int n;
for (n=1; n<=5; n++)
{
cout <<n<<”\t”<<n*n*n <<endl;
}
cout <<endl;
return 0;
}

Following is the output of the program


1 1
2 8
3 27
4 64
5 125

//Program to print factorial of a number.


#include <iostream>
using namespace std;
int main()
{ int n, k, fact;
fact=1;
cout <<”Enter a number:”;
cin >>n;
for (k=1; k<=n; k++)
{
fact = fact*k;
}
cout <<”\nFactorial is “ <<fact <<endl;
return 0;
}

M. Sajjad Heder Pg.2


//Program to print table of a number.
#include <iostream>
using namespace std;
int main()
{
int k, n;
cout <<”\nEnter a number: “;
cin >> n;
cout <<endl;
for (k=1; k<=10; k++)
{
cout <<n<<” x ” <<k<<” = ” <<n*k<<endl;
}
cout <<endl;
return 0;
}

The following will be the output of the program if n is 6.


6x1=6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
6 x 11 = 66
6 x 12 = 72

//Program to find sum of even numbers from 2 to 50.


// sum = 2 + 4 + 6 + 8 + . . . + 50
#include <iostream>
using namespace std;
int main()
{
int k, sum=0;

M. Sajjad Heder Pg.3


for (k=2; k<=50; k=k+2)
{
sum = sum + k;
}
cout <<”\nThe sum is “ <<sum <<endl;
return 0;
}

The while loop


The while loop is used to execute one or more statements repeatedly till a condition
remains true. This loop is used when we don’t know in advance how many times the loop
will execute.
It has the general form:

while (condition)
{
Block of Statements
}

When while loop is executed, the condition is evaluated. The condition is a relational
expression. If the condition is true, the Block of statements is executed. After the execution
of the statements, the control is transferred back to the beginning of the loop and the
condition is evaluated again. This process continues till the condition becomes false. When
the loop condition becomes false, the control is transferred to the next statement after the
loop. Braces are not required if a single statement is to be executed.

//Program to print the cubes of the numbers till its value is less than 600.
#include <iostream>
using namespace std;
int main()
{
int n=1, cube=1;
while(cube<600)
{
cout <<n<<”\t”<<cube <<endl;
n++;
cube=n*n*n;
}
cout <<endl;
return 0;
}

M. Sajjad Heder Pg.4


The output of the program will be:
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512

//Program to find sum of positive numbers.


//If the user enters a negative number the loop terminates.
#include <iostream>
int main()
{
int n, sum=0;
cout <<”\nEnter a number:”;
cin >>n;
while (n>=0)
{
sum = sum + n;
cout <<”\nEnter a number (negative number to quit):”;
cin >>n;
}
cout <<”\nThe sum is “ <<sum<<endl;

return 0;
}

Here is the program execution:

Enter a number: 2
Enter a number (negative number to quit):3
Enter a number (negative number to quit):4
Enter a number (negative number to quit):5

M. Sajjad Heder Pg.5


Enter a number (negative number to quit):-3
The sum is 14

The do while loop


The do while loop is used to execute one or more statements repeatedly till a condition
remains true. It is very similar to while loop, except that the loop condition is checked at the
end of the loop. Therefore, the loop is executed at least once.
It has the general form:
do
{
Block of statements
}
while (condition);
When this loop is executed, the block of statements following the do keyword is executed.
The condition at the end of the loop is evaluated. If the condition is true, control is
transferred back to the beginning of the loop. The loop is executed once again and then
condition is again checked. This process continues till the condition becomes false. When
the condition becomes false, the control is transferred to the statement after the loop. If
there is a single statement to be executed then braces are not required. The condition in
this loop is checked at the end of the loop, therefore, it is executed at least once.
//Program to convert kgs into lbs.
#include <iostream>
using namespace std;
int main()
{
int kgs, lbs;
char ch;
do
{
cout <<”\nEnter weight in kgs:”;
cin >>kgs;
lbs = kgs*2.2;
cout <<”\nWeight in lbs is “ <<lbs <<endl;
cout <<”\nDo you want to continue? (y/n):”;
cin >>ch;
}
while (ch == ‘y’);

M. Sajjad Heder Pg.6


cout <<endl;
return 0;
}

Here is the program execution:

Enter weight in kgs:4.5


Weight in lbs is 9.9
Do you want to continue? (y/n):y
Enter weight in kgs:28
Weight in lbs is 61.6
Do you want to continue? (y/n):n

//Program that reads two numbers. The first number is a dividend and the
//second number is a divisor. It then calculates the quotient and the remainder
//and prints out the result.
#include <iostream>
using namespace std;
int main()
{
int dividend, divisor;
char ch;
do
{
cout <<”\nEnter the dividend: “; cin >>dividend;
cout <<”\nEnter the divisor: “; cin >>divisor;
cout <<”\nThe quotient is “ <<dividend / divisor <<endl;
cout <<”\nThe remainder is “ <<dividend % divisor <<endl;
cout <<”\nDo another? (y/n): “;
cin >>ch;
}
while (ch==’y’);
return 0;
}

M. Sajjad Heder Pg.7


Here is the program execution:

Enter dividend: 11
Enter the divisor: 3
The quotient is 3
The remainder is 2
Do another? (y/n): y
Enter the dividend: 222
Enter the divisor: 17
The quotient is 13
The remainder is 1
Do another? (y/n): n

//Program to print all the upper-case letters on a single line.


#include <iostream>
using namespace std;
int main()
{
char ch;
ch=’A’; //It can also be ch=65:
cout <<endl;
while (ch<=’Z’) //It can also be while(ch<=90)
{
cout <<ch<<” “;
ch=ch+1;
}
cout <<endl;
return 0;
}
In the above program ch is assigned the initial value of 65 which is the ASCII value of A. Since
ch is declared as character type variable, it will print the letter A when used in the cout
statement inside the while loop. During each iteration of the loop ch is incremented by one
and goes up to 90 which is the ASCII value of Z. Therefore, the loop will print all the upper-
case letters from A to Z

M. Sajjad Heder Pg.8


The break Statement
In the previous unit we used the break statement inside a switch statement to terminate the
switch statement and transfer the control to the next statement.
The break statement can also be used to terminate a loop when it is written inside a loop
and transfer the control to the next statement following the loop.

//Program to demonstrate the use of break statement inside a for loop.


#include <iostream>
using namespace std;
int main()
{
int j;
cout <<”\n”;
for(j=10; j<=30;j++)
{
cout <<j<<”\t”;
if (j==15)
{
break;
}
}
cout <<endl;
return 0;
}
The above program will print the numbers from 10 to 15. When the value of j becomes 15,
the break statement will execute as the loop condition becomes true and the loop will
terminate.
The output of the program will be:
10 11 12 13 14 15

The continue Statement


Continue statement is used inside a loop. When it is executed, it transfers the control to the
beginning of the loop skipping the remaining statements in the loop.

//Program to demonstrate the use of continue statement in a loop.


#include <<iostream>

M. Sajjad Heder Pg.9


using namespace std;
int main()
{
char ch;
cout <<endl;
for(ch=65;ch<=90;ch++)
{
if((ch>70) && (ch<76))
{
continue;
}
cout <<ch<<” “;
}
cout <<endl;
return o;
}
The above program will print the upper-case letters from A to Z skipping those that
correspond to ASCII value 71 to 75 (G, H, I, J, K). When the value of ch is between 71 to 75,
the if condition becomes true and the continue statement is executes which transfers the
control to the beginning of the loop skipping the cout statement.
The output of the program will be:

A B C D E F L M N O P Q R S T U V W X Y Z

Nested Loops
In C++, it is allowed to nest loops within another loop. A for, while, do while loop can be
nested inside another for, while or do while loop. Loops can be mixed in any way as
required by the programmer.

//Program to demonstrate the use of for loop nested inside another for loop.
//It prints 5 lines of asterisks (*), each having 10 asterisks.
#include <iostream>
using namespace std;
int main()
{
int j, k;

M. Sajjad Heder Pg.10


for (j=1; j<=5; j++) //Outer loop executes 5 times
{
cout <<”\n”;
for (k=1; k<=10; k++) //inner loop prints a line of 10 asterisks
{
cout <<”*”;
}
}
return 0;
}

In this program, the outer loop is controlled by loop variable j and it will execute 5 time. The
inner loop is controlled by loop variable k and it executes 10 times. Each time the inner loop
is executed, it prints a line of 10 asterisks. Since the outer loop executes 5 times, the
program prints 5 lines of asterisks.

The following is the output of the program.

**********
**********
**********
**********
**********

The next program prints the following pattern using nested while loop inside a for loop.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

#include <iostream>
using namespace std;
int main()
{

M. Sajjad Heder Pg.11


int j, k;
for (j=1; j<=5; j++) //outer loop
{
k=1;
cout <<”\n”;
while (k<=j) //inner loop
{
cout <<k<<” “;
k++;
}
}
return 0;
}

M. Sajjad Heder Pg.12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy