You are on page 1of 114

LOOPS

A statement or a set of statements that is executed repeatedly is


called loop.
The statement(s) in a loop are executed for a specified number
of times or until given condition remains true.
Following is an example of a simple but important part of a
loop structure.
 i.e. for ( i=0; i<=x; i++)
Let us see first example to understand a similar introductory
fact.

1
Flow chart:

2
Example 3-01 (simple loop)
{
int c=1;
while (c<=5)
{
cout<<"Pakistan"<<endl;
cout<<“c is changing "<<endl;
c=c+1;
}
cout << "program ends since c is no more smaller than or equal
to 5" << endl;
return 0;
}
3
Example 3-01 (output)

4
LOOPS

It runs for specified times and the program ends.


If no number of times is provided, it will keep on running.

5
Example 3-01 (simple loop)
{
int c=1;
while (c<=5)
{
cout<<"Pakistan"<<endl;
cout<<“c is not changing "<<endl;
}
return 0;
}

6
Example 3-01 (output)

7
In C++, there are three kinds of loop statements. These are:
i. The “while “ loop
ii. The “for” loop
iii. The “do-while” loop

8
i. The “while” Loop
This is a conditional loop statement.
This means that it depends on the given condition, i.e. if
the condition remains true, it will keep executing.
The moment the condition is false, the program or the
loop stops.
In the example we saw above, the loop stops when c is
greater than 5. Lets see little changes in it.

9
The “while” Loop
The syntax for “while” loop is
while (condition)
statement;
The while loop for more than one statement
while (condition)
{
statement(s)
}
After the execution of the loop, if the main
condition is false,
the program shifts to whatever statement is after
the loop.
10
Flow chart:

11
Example 3-01 (simple loop)
{
int c=1;
while (c<=5)
{
cout<<"Pakistan"<<endl;
c=c+1;
}
cout << "program ends" << endl;
return 0;
}

1
2
Example 3-01 (cout)

1
3
Example 3-01 (simple loop)
{
int c;
c=3;
while
(c<=
5)
{
cout
<<
"P
aki
sta 1
4
Example 3-01 (cout)

1
5
Example 3-01 (simple loop)
{
int c;
c=3;
while
(c<=
10)
{
cout
<<
"P
aki
sta 1
6
Example 3-01 (cout)

17
Example 3-01 (simple loop)
{
int c;
c=3;
while
(c<=
10)
{
cout
<<
"P
aki
sta 18
Example 3-01 (cout)

19
The “while” Loop

In the next example we will use loop function to take sum of
first 5 odd numbers.
We will also show these odd numbers on the screen.

20
Example 3-02 (odd numbers
summation)
{ int
s, n;
s=0;
n=1;
while
(n<=10
)
{
s=s+n;
cout<<n<<endl
;
n=n+2;
21
}
Example 3-02 (cout)

1+3+5+7+9=25

22
The “while” Loop

In this example, we start with initializing s to zero and n from


1 as it represents the first odd number or the first digit in the
loop.
The upper limit is 10 to stop the loop.
In the body of the loop code, n is added with 2 to show each
odd number on the screen and then add it to the sum.
i.e. s=s+n
Let us see same program for adding first ten odd numbers.

23
Example 3-02 (odd numbers
summation)
{
int s, n;
s=0;
n=1;
while
(n<=20
)
{
s=s+n;
cout<<n<<endl
;
n=n+2;
24
}
Example 3-02 (cout)

1+3+5+7+9+11+13+15+17+19=100
25
Example 3-02 (odd numbers summation)
{
int s, n;
s=0;
n=1;
while (n<=20)
{
if(n%2!=0)
{
s=s+n;
cout<<n<<endl;
}
n=n+2;
}
cout << "The sum = "<<
s<<endl;
return 0; 26
Example 3-02 (cout)

1+3+5+7+9+11+13+15+17+19=100
27
Now make a program to add even
numbers and print odd numbers!

2
8
2
9
Example 3-02 (even numbers summation)
{
int s, n;
s=0;
n=1;
while (n<=20)
{
if(n%2!=0)
{
s=s+n+1;
cout<<“n=“<<n<<endl;
Cout<<“s=“<<s<<endl;
}
n=n+2;
}
cout << "The sum = "<<
s<<endl; 30
Example 3-02 (cout)

2+4+6+8+10+12+14+16+18+20=110 31
The “while” Loop

In the next example we use another convention to take


sum of 10 integers.
This is not much different from the previous example.

32
Example 4-1 (sum of n consecutive integers)
{
int i=1,sum=0;
while(i<=10)
{
sum+=i; //sum=sum+i
cout<<"Sum ="<<sum<<endl;
i++;
cout<<"i ="<<i<<endl;
}
cout<<"Sum is now finally:"<<sum;
return 0;
} 33
Example 4-01(output)

1+2+3+4+5+6+7+8+9+10=55 34
Example 4-01 (sum of n consecutive integers)
{
int i=1, n, sum=0;
cout<<"enter the value of n"<<endl; cin>>n;
while (i <= n)
{
sum = sum + i;
cout<<"sum ="<<sum<<endl;
i++;
}
cout << "The sum of first "<< n<<" integers is = "<<sum<<endl;
return 0;
} 35
Example 4-01(output)

1+2+3=6

36
Example 4-01(cout)

1+2+3+4+5+6=21
37
The “while” Loop

Let us take a different approach to summation and the


limit that we put for the loop.
This time we will use the while loop to sum reciprocals
first
"n“ integers
This time, the limit we will use, will have the link of the
incremented value with the sum obtained.

38
Example 4-02 (sum of reciprocals of n consecutive integers)
int n;
cout<<"Please enter the value of 'n' "<<endl; cin>>n;
float sum=0;
int i=1;
while (sum <= n)
{
sum=sum + 1.0/i;
cout<<"i="<<i<<endl;
cout<<"sum="<<sum<<endl;
i++;
}
cout << "the sum of first " <<i<<" reciprocals is "<<sum<<
endl;
return 0; 39
Example 4-02(cout)

40
Example 4-02(cout)

41
The “while” Loop
In this example, when we input "n‟, we tell the program to take
sum of reciprocals until the sum becomes less than the value
of n we gave.
For the first iteration, the program took sum of 11
reciprocals to reach a sum Equal to the value of "n‟ we
input. i.e. 3.
While, in the second iteration, it took the program 83
reciprocals to reach the sum we required.
Next we will study a program to show a column of
addition of a required number.

42
Quiz 4

4
3
Example 3-03 (column of addition)
int main()
{
int tab,c,res;
cout << "please enter the value of the number, you want to display
its addition column!" << endl;
cin>>tab;
c=1;
while(c<=10)
{
res=tab+c;
cout<<tab<<" + "<<c<<" =
"<<res<<endl; c++;
}
cout<<" This is the addition column of
"<<tab<<endl; 44
Example 4-02(cout)

45
The “while” Loop

The only difference of this example with the previous


loops here is the inclusion of a simple addition formula.
In the next example we will try to calculate the factorial
of
"n‟ number of integers.
Here the formula used for factorial is
 (n*(n-1)*(n-2)*…..*1)
n will be in descending order where as each descending
number would be multiplied.
46
Example 3-05 (Factorial)
long int fact, n;
cout<<"enter any value";
cin>>n;
fact=1;
while (n>=1)
{
fact=fact*n;
cout<<"fact="<<fact<<endl;
n=n-1;
cout<<"n="<<n<<endl;
}
cout << "finally factorial = " <<fact<< endl;
return 0;
} 47
5*4*3*2*1=120

4
8
Example 3-05(cout)

10*9*8*7*6*5*4*3*2*1=362880
49
Example 3-05(cout)

50
Example 3-07 (Descending
Order) int main( )
{
int n;
cout<<"please enter a
value"; cin>>n;
while (n!=0)
cout<<n--<<endl;
cout << "Hello world!" <<
endl;
return 0;
} 51
Example 3-07(cout)

52
5
3
Assignment:
Make a program to add numbers until user enters 0.

5
4
float number,
sum = 0.0;
cout<<"Enter a number: ";
cin>>number;
while(number != 0.0)
{
sum += number;
cout<<"Enter a number: ";
cin>>number;
}
cout<<"Total sum = "<<sum;
return 0;
5
5
Output:

5
6
The “while” Loop

Now we will use another technique to solve a


mathematics problem.
We calculate square root or in other words the under
root
of a positive integer entered by the user.
The library we will use for the function is cmath and the
function is sqrt(x) where x is any positive integer.
Lets first see a simple square root calculating program.

57
Example 4-03 (Square root)
#include<cmath> int main()
{
int x;
cout<<"Please enter a
positive integer "<<endl;
cin>>x;
cout<<"the square root of positive integer "<<x<<" is =
"<<sqrt(x)<<endl;
return 0;
}
58
Example 4-03(cout)

59
The “while” Loop

Now we will add a while loop to try a new way of


doing a loop.
We will add another user input, but within a loop.
Depending on the condition, the loop will only stop on
a specific user input.

60
Example 4-03 (Square root with multiple inputs)
{
int x;
cout<<"Please enter a positive integer "<<endl;
cin>>x;
while (x>0)
{
cout<<"square root of "<<x<<" is = " <<
sqrt(x)<<endl; cout<<"Enter another positive number
(or zero to quit) "<<endl;
cin>>x;
}
cout << "Hello world!" << endl;
return 0;
}
61
Example 4-03(cout)

62
Example 4-03(cout)

6
3
ii. The “do-while” Loop

The do-while loop is very similar to a while loop with just


the sequence changes.
Lets revise the while loop.
After the initialization phase of any program, the first part
of the loop program is the condition.
The second part is the statements under the loop or body of
the loop.
This process of condition bodycondtionbody
executes until the condition is true.
The moment the condition is false, the loop terminates.
64
The “do-while” Loop

The difference in do-while is the sequence of the steps.


Here the sequence is bodyconditionbodycondition
until the condition is false.
Then it executes whatever is after the condition.
Lets see an example to clear this point.

65
Example 3-01 (simple loop with while loop)
int main ( )
{
int c=1;
while (c<=5) //condition
{ //start of the body
cout<<"Pakistan"<<endl;
c=c+1;
} //end of the body
cout << "program ends" << endl; //after loop statement
return 0;
}

66
Example 3-01 (cout)

67
Example 3-08 (with do-while loop)

{
int c=1;
do
{ //start of the body
cout<<"Pakistan"<<endl;
c++;
} //end of the body
while (c<=5); //after loop statement
cout << endl<<"program ends" << endl;
return 0;
}

6
8
Example 3-08 (cout)

69
The “do-while” Loop
The syntax of this type of loop is
do
{
statements;
}
while (condition);
Important point here is that, there is a semicolon “ ; “
after the while condition where in the simple while
loop, there was no semicolon.
So, in the do-while loop, the program first executes
the body of
the loop and then checks the condition to repeat the 70
The “do-while” Loop

Likewise while loop, it will repeat the loop until the


condition is true.
Following is the flow chart of do-while loop.

71
“Do-while” Loop flowchart:

72
int marks;
char subject[15],name[15],op;
do
{
cout<<"Please enter Name/Subject/Marks of the student "<<endl;
cout<<"Press ENTER after each entry"<<endl;
cin>>name>>subject>>marks;
cout<<"You have entered
"<<setw(5)<<"Name="<<name<<setw(12)<<"Subject="<<subject<<setw(10)
<<"Marks=" <<marks<<endl;
cout<<"Is this information correct ? ('y' for yes or 'n' for no)"<<endl;
cin>>op;
}
while(op=='n' || op=='N');
cout << "Thank you for your input" << endl;
return 0;
} 73
Example 3-09 (cout)

74
Assignment:

Make same program with while loop.

7
5
7
6
The “do-while” Loop
Here we also use a recurring loop depending upon the input
of the user.
Here the operator yes or no in the condition is the loop
control variable.
If the user is satisfied with the input, the user inputs "y‟ or
"Y‟ and the loop terminates as the condition will recur if the
input was "n‟ or "N‟
In the above print screen case, the input was "Y‟ so the
program terminates.
In the following slide, we will see otherwise.

77
Example 3-09 (cout)

78
7
9
The “continue” statement within a Loop

In all the loops we have studied so far, we let the loop
recur for a certain number of times until the condition is
false.
Only in the case of the "sqrt‟ example, we used a loop
control variable to exit the loop when we desired.
cout<<"Enter anther positive number (or zero to quit)
"<<endl;
Keeping that in mind, we will use the next statement
that can also impact a change on how the loop
executes.
80
Example 3-08 (with do-while loop)
int main ( )
{
int c=1; //start of the body
do
{
cout<<"Pakistan"<<endl;
c++;
} //end of the body
while (c<=5); //condition

cout << endl<<"program ends" << endl; //after loop statement


return 0;
}
81
Example 3-08 (cout)

82
Example 3-08A (with do-while loop)
{
int c=1;
do
{
cout<<"Pakistan"<<endl;
c++;
continue;
cout<<"how many
times"<<endl;
cout<<"only once I
presume"<<endl;
}
while (c<=5);
cout << endl<<"program ends" 83
Example 3-08A (cout)

84
Example 3-08A (with do-while loop)
{
int c=1;
do
{
cout<<"Pakistan"<<endl;
c++;
continue;
cout<<"how many
times"<<endl;
}
while (c<=5);
cout<<"only once I presume"<<endl;
cout << endl<<"program ends" << endl;
return 0;
} 85
Example 3-08A (cout)

86
The “break” statement within a Loop

The main difference of break from continue is, continue


stops the statements under it from executing and shifts to
start of the loop while break stops the continuation of the
loop.
We will study two examples for this difference but in the
second example, we will use both things together.

87
Example 3-08A (with do-while loop)
{
int c=1;
do
{
cout<<"Pakistan"<<endl;
c++;
break;
cout<<"how many
times"<<endl;
}
while (c<=5);
cout<<"only once I presume"<<endl;
cout << endl<<"program ends" << endl;
return 0;
} 88
Example 3-08A (cout)

89
Example 3-08A (with do-while loop)
{
int c=1;
do
{
cout<<"Pakistan"<<endl;
c++;
continue;
cout<<"how many
times"<<endl;
}
while (c<=5);
cout<<"only once I presume"<<endl;
cout << endl<<"program ends" << endl;
return 0;
} 9
0
9
1
Example 3-12 (continue and break)
char name [15], op ; int age;
while (1)
{
cout<<"Enter Name ";
cin>>name;
cout<<"Enter Age ";
in>>age;
cout<<"Name= "<<name<<"\n Age=
"<<age;
cout<<"Enter more entries? [Y/N]";
cin>>op;
if(op=='Y' || op=='y')
continue;
else
break;
} 92
Example 3-08A (cout)

93
iii. The “for” Loop

The for loop can be said as a culmination of both the


previous loops and is more flexible than previous loops.
Lets see first example in case of for loop and two simple
changes to better understand it a bit.

94
Example 3-13 (for
loop) int main( )
{
int c;
for(c=1; c<=10; c+
+)
cout<<c<<endl;
cout << "Program
ends " << endl;
return 0;
}
95
Example 3-13 (cout)

80
9
6
Example 3-13 (for loop)
{
int
c;
c=1;
for(
;
c<=
10;)
{
cout
<<c<
<end
97
l;
Example 3-13 (cout)

98
Quiz 5

9
9
The “for” Loop
Please read the syntax points from the book to better
understand the ways a for loop can be written and how
variables can be initialized and incremented.
In the next example, we will try to use more than one
variable in association with the loop.
Here we will use a and b as two variables.
These two variables will be used to display ascending and
descending numbers on the screen at the same time.
a will be used for ascending and b will be used for
descending numbers.

10
0
Example 3-16 (for loop)

#include <iostream>
using namespace std;
int main()
{
int a,b;
for (a=1, b=10; a<=10; a++,
b--)
cout<<"a= "<<a<<"\t b= "<<b<<endl;
cout << "Program ends" <<
endl;
101
Example 3-16 (cout)

10
2
The Nested Loops

When we include one loop, within the body of another


loop, then it is called a nested loop.
We will use two loops in the next example.
The main loop will be the outer loop and the nested loop
here will be the inner loop.
Each time the outer loop executes, the inner loop will run
or execute x number of times with the outer loop.
Lets see an example to clarify this.

10
3
$
& & & & &

$
& & & & &

$
& & & & &

$
& & & & &

$
& & & & & 1
0
Example 3-19A (Nested loop)
{
int u=1, i;
while (u<=2)
{
i=1;
cout<<u<<endl;
while(i<=3)
{
cout<<"I Love Pakistan "<<endl;
i++;
}
u++;
}
cout << "Program ends" << endl;
return 0;
} 1
0
Example 3-19A (cout)

10
6
The Nested Loops

The outer loop(u) runs 2 times here, so each time the outer
loops runs, the inner loop (i) runs 3 times.
So, the inner loop will execute a total number of (2*3) 6
times.
Lets increase the number of times both loops run and see the
cout.
We will run outer loop 3 times and inner loop 4 times each.
Lets see the results, here outer loop will run 3 times and
inner loop a total of (3*4=12) 12 times.

10
7
Example 3-19B (Nested loop)
{
int u=1, i;
while (u<=3)
{
i=1;
cout<<u<<endl;
while(i<=4)
{
cout<<"I Love Pakistan "<<endl;
i++;
}
u++;
}
cout << "Program ends" << endl;
return 0;
} 1
0
Example 3-19B (cout)

90
1
0
int u, i,n;
Example 3-20B :
u=1;
int u, i,n; while (u<=3)
for (u=1; u<=3; u++) {
{ i=1, n=1;
n=1; while (i<=5)
for (i=1; i<=5;i++) {
{ cout<<n<<“\t”;
cout<<n<<"\t "; n=n+u;
n=n+u; i=i+1;
} }
cout<<endl;
cout<<endl;
u=u+1;
}
}
cout << "Program Ends " << endl;
cout << "Program Ends " << endl;
return 0;
return 0;
} } 11
0
Example 3-20(cout)

111
The Nested Loops
 In the above example we have used nested loop to show a table
of 3x5 values.
 The values of this table are taken from the inner loop.
 Each value shown is initiated from 1 and another value is added to
it to show the next value.
 First row, includes values that have been added to u from the
inner value.
 The values added to u are the incremented values of outer loop,
here it is I.
 In the first row, 1 is added to value of n . In the second row, 2 is
added each time to n.
 In the next example, we will use the same approach to make a
pyramid of numbers.
112
Example 3-19 (Tabular output/ pyramid of numbers):
int main()
{
int u,i;
for (u=1; u<=5; u++)
{
for (i=1; i<=u; i++)
{
cout<<"i=“<<i<<"\t ";
}
cout<<endl;
}
cout << "Program Ends " << endl;
return 0;
} 113
Example 3-19 (cout)

114

You might also like