You are on page 1of 75

CC102

Computer
Programming 2
Bhon-Bhon C.
Agcaoili
Computer Programming 2

Loop
Consider the
following problem.
Problem 1:
Write a program that will output the numbers
from 1 to 5. The output should look like:
1
2
3
4
5
Source Code Output

#include <iostream> 1
using namespace std; 2
3
int main() 4
{ 5
cout << "1 \n";
cout << "2 \n";
cout << "3 \n";
cout << "4 \n";
cout << "5 \n";
return 0;
}
• This solution solves the problem.
• However, what will happen if we
modify the problem such that we
would like to output the values from
1 to 100?
• 1,000?
• 1,000,000?
Before we do the correct solution, try to
understand the following program first:
Source Code Source Code

int ctr; #include <iostream>


ctr=1;
using namespace std;
cout << ctr << endl;
int main()
ctr=ctr+1; {
cout << ctr << endl; cout << "1 \n";
cout << "2 \n";
ctr=ctr+1;
cout << ctr << endl; cout << "3 \n";
cout << "4 \n";
ctr=ctr+1; cout << "5 \n";
cout << ctr << endl; return 0;
}
ctr=ctr+1;
cout << ctr << endl;
Notice, that the two statements,
namely:

ctr=ctr+1;
cout << ctr << endl;

are repeated several times.


They are repeated while ctr is less than
or equivalent to 5.

This key idea will allow the program to


be rewritten using loops.
What is Loop?

A loop is a control structure that allows


a statement or a group of statements to
be executed several times.
One possible algorithm for the program is as
follows:

initialize ctr to 1
repeat the following while ctr is less than or
equal equivalent to 5
print the value of ctr
increment ctr by 1
A loop usually has the following components:
• initialization
• condition
• body of loop
• change of state
In the case of the algorithm above:
initialize ctr to 1 Initialization
repeat the following while ctr is Condition
less than or equal equivalent to
5
Body of Loop
print the value of ctr
Body of Loop
increment ctr by 1
Statement that changes the
content of variable
Types of Loop

•While Loop
•For Loop
•Do While Loop
While Loop
While Loop
The while statement continually executes a block of statements
while a particular condition is true.

The syntax for the while loop is as follows:


initialization;
while (expression)
{
statement(s);
change of state;
}
Source Code Output
#include <iostream>
1
using namespace std; 2
int main()
3
{ 4
int ctr; 5
Initialization
ctr=1; Condition
while(ctr<=5)
{ Body of Loop
cout<<ctr <<endl;
ctr++;
} Change of State
return 0;
}
Exercise
1. Consider the While program. What will happen if
we remove the initialization ctr = 1? This means
that the value of ctr is not defined (garbage).
Exercise

2. Consider again the original program. What will


happen if we remove the curly brackets enclosing the
body of the loop?

Infinite Loop
Exercise
3. Consider again the original program. What will
happen if the programmer committed a typographical
error, such that instead of pressing the less than
symbol, the greater than symbol was pressed, i,e., the
condition becomes ctr>= 5 ?

The body of loop will


never be executed
Exercise

4. Consider again the original program. What will


happen when there is no ctr++?

Infinite Loop
Infinite Loop

An infinite loop (or endless loop) is a sequence of


instructions in a computer program which loops
endlessly, either due to
- the loop having no terminating condition,
- having one that can never be met, or
- one that causes the loop to start over.
Exercise

5. Write a program that will generate the numbers


from 10 down to 1, i.e., 10, 9, 8, …., 2,1.
Source Code Output
#include <iostream> 10
9
using namespace std; 8
7
int main()
6
{
int ctr; 5
4
ctr=10; 3
while(ctr>=1) 2
{ 1
cout<<ctr <<endl;
ctr--;
}
return 0;
}
The increment (decrement) of
variable needs not always 1.

Consider for example the


following:
Example 1:

Write a program that will print all the odd


numbers from 1 to 100.
Source Code Output
#include <iostream> 1
3
using namespace std; 5
7
int main()
9
{
int ctr=1; 11
13
.
while(ctr<=100) .
{ .
cout << ctr << endl; .
ctr=ctr+2; .
} 99
return 0;
}
Example 2:

Write a program that will print all the


even numbers from 1 to 100.
Source Code Output
#include <iostream> 2
4
using namespace std; 6
8
int main()
10
{
int ctr=2; 12
14
16
while(ctr<=100) 18
{ .
cout << ctr << endl; .
ctr=ctr+2; .
} .
return 0; 100
}
Variables are not limited to
integers.

Consider the following problem:


Example 3:

Write a program that will print the values


0.0, 0.2, 0.4, 0.6, 0.8, 1.0
Source Code Output
#include <iostream> 0.0
#include<stdio.h> 0.2
using namespace std; 0.4
0.6
int main() 0.8
{ 1.0
double ctr=0.0;

while(ctr<=1)
{
printf("%.1f \n", ctr);
ctr=ctr+0.2;
}
return 0;
}
For Loop
For Loop
The for loop is simply a shorthand way of expressing a while
statement.

The syntax for the for loop is as follows:

for (initialization; condition; change of state)


{
statement(s);
}
While Loop For Loop
#include <iostream> #include <iostream>
using namespace std; using namespace std;
int main()
int main()
{
int ctr; {
int ctr;
ctr=1;
while(ctr<=5) for(ctr=1; ctr<=5; ctr++)
{ {
cout<<ctr <<endl; cout<<ctr <<endl;
ctr++; }
} return 0;
return 0; }
}
To print numbers from 1 to For Loop

100 using a for loop, we can #include <iostream>


write:
using namespace std;

int main()
{

int ctr;

for(ctr= 1; ctr<=100; ctr++)


{
cout<< ctr << endl;
}

return 0;
}
To print numbers from 100 For Loop

down to 0: #include <iostream>

using namespace std;

int main()
{

int ctr;

for(ctr= 100; ctr>=0; ctr--)


{
cout<< ctr << endl;
}
}
For Loop
The for loop is actually a “more compact” form of the while loop.
The loop is executed as follows:
• perform initialization
• check the condition
• if it is true execute the statement(s); ,
• the body of loop;
• then change the state, and
• check the condition again
• if it is false, exit from the loop.
For Loop

Note that the while loop contains


• an initialization step (counter=1),
• a test step (counter<=5), and
• an increment step (counter++).
The for loop lets you put all three parts onto one line,
but you can put anything into those tree parts.
While Loop For Loop

int a,b; initialization change the state body of loop


a=1;
b=6; for(a=1, b=6; a<b; a++,cout<< a <<endl);
check the condition
while (a<b)
{
a++;
cout<< a <<endl;
}
Do While Loop
Do While Loop

• The while statement may be described as test-


before-execute.
• If the controlling expression is initially zero then the
controlled statement is never executed.
Do While Loop

• The do statement may be described as


execute-before-test.
• It is sometimes called a one-trip-loop referring to
the fact that the loop “body” is always executed at
least once.
Do While Loop
The syntax for a do-while loop is as follows:

do
{
statement(s);
change of state;
} while (expression);
Do While Loop vs While Loop
Do While Loop

#include <iostream>
To print the numbers from 1 using namespace std;
to100 using a do while loop.
int main()
{

int ctr;

ctr=1;
do
{

cout << ctr << endl;


ctr++;

} while (ctr<=100);

return 0;
}
Do While Loop

#include <iostream>
To print the numbers 100 using namespace std;
down to 0:
int main()
{

int ctr;

ctr=100;
do
{

cout << ctr << endl;


ctr--;

} while (ctr>=1);

return 0;
}
QUESTION:

Say that a program is to add up a list of numbers


entered by the user from the keyboard.

Will a loop be used in this program?


• The loop will add each integer the user enters to a
sum.
• A counting loop could do this if we knew how many
integers were in the list.
• But often users don't know this in advance, or would
find it annoying to find out.
• The idea of a sentinel controlled loop is that
there is a special value (the "sentinel") that is
used to say when the loop is done.

• In the following example, the user will enter a


zero to tell the program that the sum is
complete.
Sentinel Controlled Loop

#include <iostream>

using namespace std;

int main()
{
int sum=0, num;

do
{
cout <<"Enter an integer(enter 0 to quit): ";
cin>>num;

sum=sum+num;

} while(num!=0);

cout <<"\n\nSum of the integers: " << sum;


return 0;
}
QUESTION:

What would happen if the very first integer the


user entered were "0"?

The loop body would not execute even once.


The program would print out:

Sum of the integers: 0


PROBLEM

Write a program that will compute and display


the sum of the factorials of the numbers from 1
to n, where n is a nonnegative integer given by
the user.
Ex.
If n = 3, then compute 1! + 2! + 3! = 9; thus display 9
If n = 4, then compute 1! + 2! + 3! + 4! = 33; thus display 33
#include <iostream>
using namespace std;

int main()
{
int sum=0, num, ctr, ctr2, fact;

cout <<"Enter a number: ";


cin>>num;

for(ctr=1; ctr<=num; ctr++)


{
fact=1;
for(ctr2=1; ctr2<=ctr; ctr2++)
{
fact=fact*ctr2;

}
sum=sum+fact;
}

cout <<"\n\nSum of " << num << " factorial is " << sum;
return 0;
}
Nested Loop

• it is possible to have a loop inside a loop, may


it be a while, a for or a do while loop.
• We called this loop as a nested loop.
Problem

Use a nested while loop to construct the 10 x 10


multiplication table.
#include <iostream>
using namespace std;
int main()
{
int i,j;

i=1;
while(i<=10)
{
j=1;
while(j<=10)
{
cout << "\t" << i*j;
j++;
}
cout << "\n";
i++;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i,j;

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


{
for(j=1; j<=10; j++)
cout << "\t" << i*j;

cout << "\n";


}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int i,j;

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


{
j=1;
while(j<=10)
{
cout << "\t" << i*j;
j++;
}
cout << "\n";
}
return 0;
}
Break statement

1. The break statement


2. The continue statement
Break statement

• Sometimes we need to exit from a loop before


the completion of the loop then we use break
statement and exit from the loop and loop is
terminated.
• The break statement is used in while loop, do -
while loop, for loop and also used in the switch
statement.
string uname="", pword="";
char resp;
do
{
cout<<"Enter username: ";
cin>>uname;
cout<<"Enter password: ";
cin>>pword;

if(uname=="admin" && pword=="admin")


{
cout<<"\nAccess granted!\n\n";
break;
}
else
{
cout<<"Access denied! \n\n";
cout<<"Try again?[Y/N]:";
cin>> resp;
}

}while(resp=='Y' || resp=='y');

cout<<"Thank you!\n";
Continue statement

• Sometimes we do not need to execute some


statements under the loop then we use the
continue statement that stops the normal flow
of the control and control returns to the loop
without executing the statements written after
the continue statement.
Continue statement

• There is the difference between break and


continue statement that
• the break statement exit control from the loop
• but continue statement keeps continuity in
loop without executing the statement written
after the continue statement according to the
conditions.
Source Code Output

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

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


{
cout << ctr << endl;

if (ctr == 2)
{
//loop will now stop
break;
}
}
return 0;
}
Source Code Output

#include <iostream>

using namespace std;

int main()
{
int ctr;
for ( ctr = 1 ; ctr <= 10 ; ctr++ )
{
cout<<"\n"<< ctr << "\t";

if ( ctr == 2 )
{
continue;
}
cout<<"ctr is not 2";
}
return 0;
}
Summary
• A loop is a control structure that allows a statement or a
group of statements to be executed several times.

• A loop usually has the following components:


• initialization
• condition
• body of loop
• change of state
Summary
• There are three types of loop
• While Loop
• For Loop
• Do While Loop

• The while statement continually executes a block of


statements while a particular condition is true.
• The while statement may be described as test-before-
execute.
Summary
• The for loop is simply a shorthand way of
expressing a while statement.

• The do loop may be described as execute-before-test.


The loop “body” is always executed at least once.

• In a sentinel controlled loop, there is a special


value (the "sentinel") that is used to say when the
loop is done.
Summary
• It is possible to have a loop inside a loop,
may it be a while, a for or a do while loop.
We called this loop as a nested loop.

• An infinite loop (or endless loop) is a


sequence of instructions in a computer
program which loops endlessly
Summary
• break statement exit control from the loop

• continue statement keeps continuity in loop


without executing the statement written after
the continue statement according to the
conditions.
-Bhon-Bhob C. Agcaoili

You might also like