0% found this document useful (0 votes)
22 views14 pages

Lecture 4 Loops-1

Uploaded by

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

Lecture 4 Loops-1

Uploaded by

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

Loops

Loops are iteration statements. Loop provides a mechanism to execute same


sequence of instructions repeatedly until a condition is reached. There are two
elements of the loop: the body of loop which is to be executed number of times and
a loop condition which terminates the loop when a particular condition is met.
The three different kinds of a loop are: -

 The for loop


 The while loop
 The do while loop

The for loop

The for loop is used to execute same sequence of statements for the predetermined
number of times.

The general form of the for loop is: -

for (initialization; condition; iteration_expression)

statement;

The initialization is used to initialize the control variable of the loop. The
initialization is executed once at the beginning of the loop. The condition is
checked at the beginning of every iteration and if the condition is false then the
loop is terminated. The iteration_expression is executed at the end of each loop
iteration. It modifies the control variables of the loop initialized in the beginning.
Here is a program which illustrates the working of the for loop.

1
Examples:
1. (a) Write a C++ program that adds all numbers between 1 and 10 inclusive
#include<iostream.h>

int main()
{
int total=0;
// this loop adds the numbers 1 through 10 to the variable total
for (int i=1; i < 11; i++)
{
total = total + i;
}
cout<<total<<endl;
return 0;

(b) Exercise

Write a for loop to produce all integer numbers between 5 and 12 inclusive

#include<iostream.h>

int main( )
{ int x;
cout << "Numbers between 5 and 12 are ";
for (x = 5; x <= 12; x++)
{
cout << x << " ";
}
cout << endl << endl;

return 0; }

2
The program is used to calculate the sum of first 10 numbers using a loop. There are
10 iterations of the loop. The variable c is initialized to zero. In the statement

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

i=1; is the initialization expression which sets the value of control variable to be 1.
The condition is

i<=10;

and at the beginning of each iteration this condition is checked whether the value of
variable i exceeds value 10 . The iteration_expression is

i++;

and at the end of each iteration the value if variable i is incremented by 1. In the
body of the loop the statement

3
cout << i << endl;

prints the value of i for every iteration and the statement

c=c+i;

computes the sum of the values of the variable i. At the last iteration the value of the
variable i becomes 11 when statement i++; is executed and then the condition i<=10;
is checked and now the condition is false and as a result the loop is terminated. The
control of the program is transferred to the statement following the for loop. The
statement

cout << “The sum is” << c << endl;

is executed and which prints the sum as 55.

In the for loop, the body of the loop is never executed if the condition is false at the
beginning of the first iteration. There are many variations of the for loop. User can
use comma operator to declare two or more variables to control the loop. For
example,

for(int i=0 , int j=0; i+j<=10; i++)

j++;

variables i and j are controlling the loop. The statement int i=0, int j=0; are
initialization statements.

Example 3: Example of a countdown using for loop

// countdown using a for loop


#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

We can also count backward with a for loop


4
int main()
{
// declare a variable before starting
int i;
for(i=10; i > -1; i--)
{
if(i == 0)
cout << "Blast Off!" << endl;
else
cout << i << endl;
}

The While Loop

The while loop uses a condition to control the execution of the body of the loop. The
general form the while loop is: -

while(condition)
{
statement;
}

The condition is an expression which is executed at the beginning of each


iteration. If the condition is true then the body of the loop is executed and if it is
false loop is terminated and control is transferred to the statement following the
while loop. The condition evaluates to a type bool, or to a value of an integer type. If
the condition produces the integer, the loop will execute as long as integer is non
zero. Non zero integer is converted to type bool as true and if the value of integer is
zero it is taken as false. Here is the program which illustrates the working of while
loop.

Example 1

Use the while loop to print all even numbers between 11 and 23
5
#include <iostream.h>

int main()
{
int current_number = 12;

// while loop that prints all even numbers between 11 and 23 screen
while (current_number < 23)
{
cout << current_number << endl;
current_number += 2;
}
cout << "all done" << endl;
}

Example 2:

In the program value of the variable i is incremented by 1 in each iteration. The


condition

i<10

checks whether the value of i is less than 10 in every iteration. In every iteration of
the loop value of i is incremented by 1 by the statement

i=i+1;

In the last iteration the value of i becomes 10. Then the condition is checked and it
returns false, loop is terminated and control is transferred to the statement
6
return(0);

Example 3 :

Custom countdown using while

#include <iostream.h>

int main ()
{
int n;
cout << "Enter the starting number "<<endl;
cin >> n;

while (n>0)
{
cout << n << ", ";
--n;
}

cout << "FIRE!\n";


return 0;
}

Interpretation

When the program starts the user is prompted to insert a starting number for the
countdown. Then the while loop begins, if the value entered by the user fulfills the
condition n>0 (that n is greater than zero) the block that follows the condition will be
executed and repeated while the condition (n>0) remains being true.

The do while loop

The do while loop works same as the while loop and the loop is iterated as long as
condition remains true. The do while loop checks the condition at the bottom of
the loop while for and while loop checks the condition at the beginning of the
loop and as a result the body of the loop is executed at least once. The general form
of the do while loop is: -

do{

statement;

} while(condition);
7
The body of the loop is executed until the condition becomes false. Here is a
program which illustrates the working of the do while loop.

Example: For example, the following example program echoes any number you
enter until you enter 0.

// number echoer

#include <iostream.h>

int main ()
{
unsigned long n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}

NOTE

The do-while loop is usually used when the condition that has to determine the end
of the loop is determined within the loop statement itself, like in the previous case,
where the user input within the block is what is used to determine if the loop has to
end. In fact if you never enter the value 0 in the previous example you can be
prompted for more numbers forever.

8
In the program the condition is checked at the end of the loop by the statement

while(str==’y’);

The body of the loop is iterated once without checking the given condition. The
statements

cout << “Enter the number you want to add” << endl;

cin >>i;

allow the user to enter the number to be added. Then the statements

cout << “Do you want to enter the number y/n” << endl;

cin >> str;

ask the user whether he or she wants to add another number. If the user enters ‘y’
then the condition is true and the loop is executed once more. If the user enters any
character other than ‘y’ then the condition is false and loop is terminated.

9
Switch Statement

The switch statement is a type of control structure. The general form of a switch
statement is

switch (expression)

case constant 1 :

statement sequence

break;

case constant 2 :

statement sequence

break;

default:

statement sequence

The switch statement allows doing multiple selections depending upon the value
of expression. It tests the value of the expression against the integer or character
constants. The value of the expression must be integer or character. The value of
the expression is tested against the constants in the case statements. When a
correct match is found sequence of statements associated with the constant is
executed until the break statement or the end of the switch statement is reached. If
no match is found then sequence of statements associated with default is
executed. The case values appear in case labels. No two or more case labels can
contain same constant values. The case values can occur in any sequence. Here is a
program which illustrates the working of switch statement.

10
The user has entered the number 3 corresponding to the statement

cin >> c;

The value of variable c is now 3. The switch statement

switch(c)

is now executed. The value of the variable c is matched against the constants in the
case statements. The value matches with the constant 3 in the case label and as a
result the statement

cout << “ You have chosen cookies” << endl;

is executed. The statement


11
break ;

switches the control to the statement following the switch which is the statement

return(0);

If the user has entered value other than the constants in the case labels then the
statement associated with the default would have been executed.

Now the user has entered the value 7. The value of variable c is 7. The value 7 does
not match with any of the constants in the case labels and as a result statement

cout << “ You have not chosen any item” << endl;

is executed.

The break statement is necessary as it switches the control to the statement following
the switch statement after executing sequence of statements associated with case
value. If the break statement is omitted then the sequence of statements for all the
following cases are executed till a break statement is encountered or end of the
switch is reached. Here is a program which shows how the statements are executed
when there is no break statement.

The user has entered value 1. The value of the variable c is 1. The switch statement is
executed. The value of the variable c is matched against the constants in the case

12
labels. It matches with the value of the first case statement. As there is no break
statement the execution is transferred to the statement

case (2) :

As there is no break statement associated with this case statement also the control is
transferred to the third case statement

case (3) :

The next statement

cout << “ You have chosen one of the first 3 items” << endl;

is executed. Then the statement

break;

is executed and control is transferred to the statement following the switch


statement. Omitting the break statement can be helpful when sequence of statements
for two or more case statements is same. For example, in this program statement

cout << You have chosen one of the first 3 items “ <<

is same for first 3 case statements. Instead of typing the same statement along with
every case label you can ignore the break statement with the case statements and
insert the break statement where termination is necessary. It avoids unnecessary
duplication of sequence of statements.

The statement switch can be used instead of if statement. Instead of using ifs
statements for checking the expression against two or more constant values, switch
should be used. Here is a program which performs the same function but uses ifs
statements.

13
The task of writing nested ifs is tedious and switch should be used.

14

You might also like