Sie sind auf Seite 1von 19

PROGRAMMING WITH C++/Lec5

LOOP STATEMENTS 1
The loop statements are essential to construct systematic block styled programming .In C++, there are various ways
one may define the control structures using the different types of loop operations. Sometimes other high level
languages may not support all the features of the C++ control structures. The following loop structures are supported
by C++:
(l) for loop
(2) while loop
(3) do-while Loop

3.3.1 for Loop


The f or loop is the most commonly used statement in C++. This loop consists of three expressions. The first
expression is used to initialize the index value, the second to check whether or not the loop is to be continued again
and the third to change the index value for further iteration. Sometimes, the operations carried out by the while loop
can also be done by using the f or loop. However, it is the programmer who has to decide which loop to be used in
a given situation. The syntax of the f or loop is:
for ( expression_1; expression_2 ; expression_3)
statement;

where expression_1 is the initialization of the expression or the condition ; expression_2 is the condition checked as
long as the given expression is true; and expresion_3 is the incrementer or decrementer to change the index value of
the f or loop variable. Grammatically, out of the three components of a for expression, most commonly expression-1
and expresion-3 are assignments and expression_2 is a relational expression.

In other words,
for ( initial condition; test condition; incrementer or decrementer) {
statement_1.
statement_2
----------------------------------}

Thus consider a simple example shown below,


Sum = 0;
for (i=0; i<=100; ++i)
sum = sum+ i ;

Amir.Y.Mahdi

The loop variable in this case is i. During the first pass; this variable is initialized with the value 1. In subsequent
passes, this step will not be carried out. ,After initialization is done, the second expression is evaluated and the loop is
entered only if it is true. The loop statements are executed and then the third expression is evaluated. The result is the
incrementing of i by 1.

# PROGRAM
A program to display numbers from 0 to 10 using the for loop. .,

/ / example

#include <iostream.h>
void main (void)
{
For (int i = 0; i<= 10; ++i) {
cout << i << '\t' ;
}
}

# PROGRAM
A program to find the sum and average of given numbers.

// example
#include <iostream.h>
void main (void)
{
int n ;
cout << "How many numbers ? \n";
cin>>n;
float sum = 0;
float a ;
for (int i = 0; i<= n-1;++i) {
cout <<"Enter a number \n ";
cin >>a;
sum = sum+a;
}

float av ;
av = sum/n;
cout <<"sum =" << sum << endl;
cout<<" Average = "<<av<<endl;

Amir.Y.Mahdi

// 72
Cout.put (ch);
}
}
The for loop is used to read a character from the keyboard as long as the test condition is being a new line or a
carriage return.
Type 2 Sometimes, one may enter the for loop as:
For ( ; ; )
Here , the for loop is valid but it will execute the loop indefinitely because there is no condition to be checked to
terminate this loop .
Type 3 Another type of for loop is :
For ( i=0 ; I <=9 ; i++) ;
This loop will be repeated till the I value becomes 9 . There is no statement used in this loop and the semicolon is
used for terminating the loop . It will just repeat the loop operation as long as the given condition becomes true . One
may require this type of operation for introducing time delay in a program .
Type 4 The comma operator can be used in conjunction with the for statement which permits two different
expressions to appear in a situation where only one expression would ordinarily be used.
The general syntax of the for statement with comma operator ,
For ( experession_1a , expression_1b ; expression_2; expression_3)
{
Statements
Statements
}
Where expression_1a and expression_1b are the two expressions by the comma operator and normally only
expression_1 would appear .
The two expression would typically initialize two separate indices that would be used simultaneously within the for
loop.
Another way of using the comma operator in a for statement is :
For ( expression_1; expression_2; expression_3a,expression_3b)
{
Statement
Statement
}
Amir.Y.Mahdi

Here, expression_3a and expression_3b, separated by the comma operator , appear in place of a single expression ,
expression_3. In this application , two separate expressions would typically be used to alter (e.g. incrementer or
decrementer) the two different indices used simultaneously within the loop. For example , one index may count
forward while the other backward.
# PROGRAM
A program is used to display the number between 0 to 9 as well as 9 to 0 simultaneously :
one by one .

main ( )
{
for (int i =0, j= 9 ; i<=9 ; i++ , j-- ){
cout<< "i = " << i <<' \t '<<" j = " << j << endl;
}
}

Output of the above program


i= 0 j=9
i= 1 j=8
i= 2 j=7
i= 3 j=6
i= 4 j=5
i= 5 j=4
i= 6 j=3
i= 7 j=2
i= 8 j=1
i= 9 j=0

Invalid way of data initialization

The following illustrations indicate in general the wrong

ways adopted to initialize data.

(1)
for (int i=0, int j =10; i <=n; ++i, j--) / / int j is wrong
(2)
Int j ;
for (int i=0, J= 9; i <=n; ++I ; j--)

Nested for loops

/ / declaration of j repeats

Normally, any loop will be placed inside the other loop in C++. Just

for an example , the following program segment shows the for loop within one more
for loop.

Amir.Y.Mahdi

for ( i = 0 ; i <= 2 ; ++i ) {


for ( j =0; j <= 2 ; ++j )
statements
statements
-------------------------------}
# program

A program to display a name 15 times using ,the nested for loops.

/ / example
/ / nested for loop of 27 times

#include <iostream.h>
void main (void)
{
cout <<" Explaing the nested for loop \n";
for ( int i=0; i<=2 ;++i) {
cout<<I;
for ( int j=0; j = 2; j++) {
cout <<j;
for ( int k=0 ; k<= 2 ; k++) {
cout<< " my name is a computer \n ";
}
} / / end of j loop
} / / end of I loop
} / / end of main program

while Loop .
The second type of loop, the while loop, is used when we are not certain that the loop
will be executed. After checking whether the initial condition is true or .false and
finding it to be true, only then the while loop will enter into the loop operations.

The general form of the while loop is :


For a single statement,
while (condition)
statement;
For a block of statement ,
While (condition){
Statement_1;
Statement_2;
Amir.Y.Mahdi

-----------------------------------}

The condition can be any valid C++ language expression including the value of a variable, a unary or binary
expression, or the value returned by a function. The statement can be a single or a compound statement. The
conditions actually the test condition.
The while loop does not explicitly contain the initialization ,or incrementation parts of the loop. These two statements
are normally provided by the programmers.

initial condition
while ( test condition )
{
statement_1 ;
statement _2 ;
change of the intial condition ;
}

The while loop without initialization and incremenation parts is,


while ((character = cin.get() ) != EOF)
cout.put (character);

As long as the character is not an EOF character, while loop reads a character from
the keyboard and displays it on the screen.

The following program segments show the use of the initial condition and the test condition to be used in the
program. This program is used to find the sum of the first 100 natural numbers.
# PROGRAM
A program to find the sum of the first 100 natural numbers.
Sum=1+2+3+100
/ / example 3.12
# inctrude<iostream. h>
void main (void)
{
int sum , digit;
sum = 0;
digit = 1;
while ( digit <= t00) {
sum += digit;
digit++;
}
cout <<" 1+2+3+.100 ="<<sum <<endl;
}
Amir.Y.Mahdi

Output of the above program


1,+2+3+.. 100 = 5050
.tn the above program, the initial condition is assigned to 0 and the test condition is used to check whether the digit
value has become 100 . If not , it will repeat the loop. The final statement of the program digit++ will be incremented
by one during each execution for changing the initial index value

# PROGRAM

A program to display the first 100 odd numbers using the while loop.

/ / example 3 .13
#include <iostream.h>
void main (void) ,
{
Int x , x_max;
Cout<< " first 100 odd numbers \n ";
x=1;
x_max = L00;
while ( x <= x_max) {
cout<< " x = "<<x<<endl;
x = x + 2;
}
}

# PROGRAM

A program to find the sum and average of the given numbers using the while loop.
/ / example
#include <iostream.h>
void main (void)
{
int n ,I ;
Float av , a , sum ;
Cout<< " how many number ? \n";
Cin>> n;
I=0;
Sum=0;
While (i<=n-1) {
Cout<<" enter a number \n ";

Amir.Y.Mahdi

Cin>>a ;
Sum = sum +a;
++ I;
}
Av = sum/n;
Cout<<" sum= "<<sum << '\t';
Cout<< " average =" << av <<endl;
}

Role of incretnenter and decrementer in C+ + One must be always cautious. While using the incrementer or
decrementer as i++ and ++i. The following program segment to find the sum of the first 10 numbers shows the
distinct use of the two types of incrementers .
(1)
Sum = 0;
I=1;
While (i<=10)
sum += i++;
(2)
sum = 0;
1 =1;
While(I <=10)
sum += ++i;
In both cases, the sum will be the same but in the first case, the i exists with i = 11 and the second case it exists with i
= 10.
Consider another program segment to compute the sum of the first 100 numbers, as
given below:

Sum = 0;
i=1;
while (i<100){
sum1 += i++;
sum2 += ++i;
}
At the end, sum1 will be calculated for 99, and the sum2 will be 101.

Use of while loop to input data Normally, the while loop is used for reading data and processing it until the end of
data is found. The above use is illustrated through a program segment which reads a set of characters from the
keyboard until it finds a carriage return key or a new line and displays it on the video screen.

Amir.Y.Mahdi

/ / reading a line of characters using while loop


# include <iostream .h>
Void main (void)
{
Char ch;
Cout<<" enter a line \n";
Ch=cin.get ();
While (ch != '\n' ){
Cout.put(ch);
Ch=cin.get();
}
}

Another compact C++ code is ,


/ / reading a line of characters using while loop
/ / version 2.cpp
#include <iostream.h>
void main (void)
{
Char ch;
Cout<< " enter a line \n ";
While ((ch = cin.get ()) != '\n '){
}
}
Cout.put (ch) ;
}
}

Sometimes, one may use more than one test condition using different logical expressions as a single statement. For
example, one expression can be used to check both the new line and the tab character.
ch = cin.get ( )
while ( ch != ' \n ' && ch != '\ t ' ) {
------------------------------------}
/ / check for a line feed and tab of a given character
#include <iostream.h>
void :main (void) :
{
char ch;
cout <<" enter a line \n ";
ch =cin.get ( );
Amir.Y.Mahdi

while ( ch != '\n' && ch != '\t' ){


cout.put (ch) ;
ch =cin.get( );
}
}

do-while Loop

The do-whiIe loop is another repetitive loop used in C++ programs. Whenever one is certain about a test condition,
then the do-while loop can be used; as it enters into the loop at least once and then chicks whether the given condition
is true or false. As long as the test condition is true, the loop operations or statements will be repeated again and
again. As in the case of a while loop, here also three expressions are used to construct this loop. Expresslon_1,is used
to initialize the index value that normally appears out of the loop; expression_2 , to change the index value and the
expression 3 to check whether or not the loop is to be repeated again.
The general syntax of the do-while loop is :
Do {
Statement_1
Statement_2
___________
___________

while (expression);

In other words, the above do-while loop is equivalent to :

Expression_1
Do {
Statement_1
statement _2
__________
__________
Expression_2
}
while (expression_3);

The use of the do-while loop is illustrated through the following programs.

Amir.Y.Mahdi

11

# PROGRAM 3.14
A program to find sum of the even numbers using do-while loop.
Sum = 2+4+6...n

/ / example 3.15
/ / sum = 2+4+6...
#include (iostream.h)
void main (void)
{
int max, sum, digit ;
diqit = 2;
cout<< " enter a number \n ";
cin>> max;
sum=0;
do {
sum = sum + digit;
digit = digit +2;
}
While (digit <= max);
Cout<< " 2+4+.= " <<max << " sum = ";
Cout<<sum<<endl;
}

Output of the above program


Enter a number
2+4+..=10 sum= 30

# program

A program to find the sum and average of the given numbers using the do-while loop .
/ / sum and average of the given numbers
/ / using do-while loop
# include <iostream.h>
Void main (void)
{
Int n , I ;
Float av , a , sum ;
Cout<<" how many numbers ? \n";
Cin>>n;
I=0 ; sum=0;
Do {
Cout<<< " enter a number \n";
Cin>>a;
Amir.Y.Mahdi

11

Sum = sum +a;


I++;
}
While(i<= n-1);
Av=sum/n;
Cout<<"sum " <<sum <<endl;
Cout<<" average = " << av << endl;
}

BREAKING CONTROL STATEMENTS

For effective handling of the loop statements, C++ allows the use of the following three
types of control break statements:

(1) break statement


(2) continue statement
(3) goto statement

break Statement
The break statement is used to terminate the control from the loop statements .of the case-switch structure. The break
statement is normally used in the switch-case loop and in each case condition, the break statement must be used. If
not, the control will be transferred to the subsequent case condition also.
The general format of the break statement is :
break;

The break is a keyword in the C++ program and the semicolon must be inserted after
the break statement. Two uses of the break statements are illustrated below:

(1) Break statement used with switch-case structure

switch(day) {
case '1' :
cout<< " Monday \n ";
break;
case '2' :
cout<<" Tuesday \n";
break;
default :
----------------------------}/ / end of swit.ch-case structure

Amir.Y.Mahdi

12

If we have written the switch-case structure like this,


switch (day) {
case '1' :
cout<<"Monday \n";
case '2' :
cout<<" Tuesday \n";
break;
default :
----------------------------}/ / end of swit.ch-case structure

then the computer will print the message like this


Monday
Tuesday
Since there is no break statement in the case 1, the computer will transfer the control to other cases also. To avoid this
sort of undesired results, normally the break statement will be used in the each case section but not in the last case
section as the control will automatically be back to this section.

(2) break statement used in a while loop

A break statement is used in other loops also and it is explained with the following
illustration:
/ / using break statement inside the while
#include <iostream.h>
void main (void)
{
int value , I ;
i = 0;
while ( i<=10) {
cout<< " enter a number \n";
cin>> value;
if (value <=0){
cout<<" zero or negative value found \n ";
break;
}
I++;
}
}

The above program segment will process only the positive integers. Whenever a zero
or negative value is encountered, the computer will display the message "Zero or
Amir.Y.Mahdi

13

negative value f ound" as an error and exit from the while loop.

3.4.2 continue Statement

The continue statement is used to repeat the same operations once again even if it
checks the error.
The general syntax of the continue statement is,
continue;
continue is a keyword followed by the semicolon.
The continue statement is used for the inverse operation of the break statement

The following program segment illustrates the use of the continue statement operation.
/ / using continue statement inside the while loop
#.inctrude <iostream.h>
{
Int value , I ;
I=0;
While (i<=10){
Cout<<" enter a number \n";
cin >> value;
if ( value <= 0) {
cout << " zero or negative value found \n;
continue;
}
I++;
}
}
This program segment will process only the positive integers. Whenever a zero or
negativevalueisencountered,thecomputerwiIldisplaythemeSsage"Zero or
negative value found" as an error and it continues the same loop as long as the given condition is satisfied.
Use of continue statement in a while loop The break statement is used in the
other loops also which is explained in the following illustration:
cin >> value;
while (value <= 100 ) {
if (value <= 0) ;
cout <" Zero or negative value found \n ";
continue;
}
}/ / end of while loop

The above program segment will process only the positive integers .Wlhen ever a zero
or negative value is encountered, the computer will display the message "zero or
Amir.Y.Mahdi

14

negative value found" as an error and it continues the same loop as long as ,the
given condition is satisfied.

goto Statement
The goto statement is used to alter the program execution sequence by transferring the control to some other part of
the program The general syntax of the goto statement is :
goto label;
where label is a valid C++ identifier used to label the destination such that control
could be transferred.
There are two ways of using the goto statements in a program, namely, as a
conditional goto and as an unconditional goto.

(a) Unconditional goto The unconditional goto statement is used just to transfer the
.control from one part of the program .to the other part without checking any condition.
Normally, a good programmer will not prefer to use the unconditional goto statement in
his program as it may lead to a very complicated problem like a never ending
process. The use of unconditional goto statement is illustrated in the following

//unconditional goto statement


#clude <iostream. h>
void main ( )
{
Start :
cout << "My name is Komputer \n";
goto start ;
}

(b) Conditional goto The conditional goto is used to transfer the control of the
execution from one part of the program to the other in certain conditional cases.
The following sample programs explain the use of conditional goto statements.

Illastration 1
/ /conditional goto statement
#inc]ude <iostream. h>
void main ( )
{
Int a,b;
cin >> a >> b;
if (a>b)
goto output1;
else
goto output2;
output1;
Amir.Y.Mahdi

15

goto stop;

output 2 :
cout<< " largest value = " << b << end ;
stop:
}

Illustration 2
The goto statement can be used in a while loop as illustrated in the following program segment which checks the
possible negative or zero values in the input data whenever it is non-zero or positive , and continues the while loop.

/ / use of goto statement inside the while loop


#include<iostream.h>
Void main (void)
{
Int value , I ;
I = 0;
While (i<=10){
Cout<< " enter a number \n ";
Cin>> value ;
If ( value <=0){
Cout<< " zero or negative value found \n";
Goto error;
}
I++;
Error:
Cout<<" input data error /n";
}

Output of the above program

Enter a number
1
Enter a numbr
0
Zero or negative value found
Input data error

Amir.Y.Mahdi

16

REVIEW QUESTIONS
1. What is meant by the conditional expression?
2. What is a nested if statement?
3. When two if statements are nested, what is the rule that determines which else
clause matches which if ?
4. What is the difference between the two operators = and == ?
5. What are the different ways of constructing a multi way if -else structure?
6. What is the switch-case statement and how is it different from the multi way
if -else structure?
7. What is meant by the break statement and how it is involved in constructing a
Multi way switch- case structure?
8. What is looping in C++? What are the advantages of using loops in C++?
9,WhatarethedifferenttypesofloopstatementsusedinC++?
10. What is f or loop? Under what circumstances the f or loop is used to construct a
looping in C++?
11. what are nested for loops?
12. What is a while loop and how does it vary from the f or loop?
13. What is the appropriate place or circumstance under which the while loop is better
than the f or loop?
14. What is the do-while loop?
15. How the do-whi1e loop varies from the while loop? Explain.
16. Explain the following loop control statement in C++.
(a) break statement
(b) continue statement
(c) goto statement
17. What is the use of a continue statement in C++?
18. List out the merits and demerits of while loop and do-whi1e loop?
19. Why is goto not necessary for a structured programming language like C++?
20.Summarize the syntactic rules of the following loop statements:
(a) for loop
(c) do-whiIe loop
(b) while loop

21.What is the purpose of the comma operator? Between which statements does the
comma operator usually appear?

PROGRAMMING EXERCISES
1.write a program in C++ to find the square of the numbers from I to 100 using
(i) for loop
(ii) while loop
(iii) do-whi1e loop
The output should be as follows :
Number
Amir.Y.Mahdi

Square
17

---------

---------

----------

---------

2.Modify the above original program so that it prints the squares (only the squares,
not the numbers) of all numbers from I to 125, each on its own line. It should
print 1 , 4. 9, 16, 25 and so on.

3.Write a program in C++ that prints the numbers and its cube from 1 to 10 using the
following control statements:
(i) if-then-e1se (ii) for loop
(iii) while loop (iv) do-whi1e loop

4. Modify the above program so that it prints the number, square and the cubes of only
odd numbers from 0 to 100. The output should be like
Number

Square Cube

---------

---------- --------

---------

---------- --------

5. Modify program 4 so that it prints the number, squer, and cubes of only even
numbers from 0 to 100 with the same output.

6. Write a program in C++ that will print all the numbers less than 2000 that are
evenly divisible by 10 using
(i) if-then-else and goto statement
(ii) for loop
(iii)

while loop

(iv)

do_while loop

The output should be like l0 20 30 ...

write a program in C++ to find the sum of the following series using
(i) f or loop (ii) while Ioop (iii) do-while roop (iv) goto statement (v) continue statement

(a) sum=l+2+3+...+n
(b) sum= 1+3+5+...+n
(c) sum=l+2+4+...+n
(d) sum= 1- 1/1! + 2/2! 3/3! .n/n!
(e) sum = x+x2/2! +x4/4! + x6/6! + xn/n!
(f) sum = x-x3/3! +x5/5! - x7/7! + xn/n!
(g) sum = 12 + 22 + 32 +42+.+n2
(h) sum = 13 - 23 + 33 -43+.-n3
(i) sum = 1 + 22 +42+.+n2
(j) sum = 1 32 +52-.+n3
Amir.Y.Mahdi

18

8.Write a program in c++ to generate the following series of number :

(i)

(ii)

2 1

1 2

3 2 1

1 2

4 3 2 1

1 2

3 4

5 4 3 2 1

1 2

3 4 5

6 5 4 3 2 1

1 2

3 4 5 6

7 6 5 4 3 2 1

1 2

3 4 5 6 7

8 7 6 5 4 3 2 1

1 2

3 4 5 6 7 8

9 8 7 6 5 4 3 2 1

1 2

3 4 5 6 7 8 9

(iii)

(iv)

9 8 7 6 5 4 3 2 1

1 2 3 4 5 6 7 8 9

8 7 6 5 4 3 2 1

1 2 3 4 5 6 7 8

7 6 5 4 3 2 1

1 2 3 4 5 6 7

6 5 4 3 2 1

1 2 3 4 5 6

5 4 3 2 1

1 2 3 4 5

4 3 2 1

1 2 3 4

3 2 1

1 2 3

2 1

1 2

9. Write a program in c++ that prints the factorial of a given number using
(i) for loop (ii) while loop (iii) do-while loop

Amir.Y.Mahdi

19

Das könnte Ihnen auch gefallen