You are on page 1of 108

Loops

Chapter 3

1
Loops (Iterative statements)
• The other main type of control statement is the
loop. Loops allow a statement, or block of
statements, to be repeated. Each execution of a
loop is known as an iteration. Repetition
control statements allow the programmer to
specify actions which are to be repeated while
some condition is true.

2
C gives you a choice of three types of loops

1. The while loop keeps repeating an action until an


associated test returns false. This is useful where
the programmer does not know in advance how
many times the loop will be traversed.
2. The do while loop is similar, but the test occurs
after the loop body is executed. This ensures that
the loop body is run at least once.
3. The for loop is frequently used, usually where
the loop will be traversed a fixed number of
times.
3
The while Loop
The simplest kind of loop is the while-loop. Its
syntax is:

while( boolean-expression )
{
loop body statements;
}

4
• The boolean expression (condition) is tested, if
the result of the expression is true then the
loop body is executed. After every iteration,
the expression is tested again and the loop
body is executed depending on whether the
result is true. If the result is false, then the loop
is terminated and the program execution
continues with the statements following the
while loop.
5
Example: count down
void main ()
{
int n = 10;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << “Byebye\n";
}
6
The output of executing the program
will be as follows
• 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Byebye

7
• A thing to consider with while-loops is that the
loop should end at some point, and thus the
statement shall alter values checked in the
condition in some way, so as to force it to
become false at some point. Otherwise, the
loop will continue looping forever.

8
Note
• If the Boolean expression is initially false the
statements (or statement) are not executed. If
we modify the initialization value of n in the
previous example to be a negative number, the
Boolean condition becomes false. No numbers
will be printed.

9
The do while Loop
The while loop evaluates a condition or expression
before executing the loop. Therefore the body of the
loop is never executed if the conditions are not met
at the start. Sometimes it is necessary to evaluate the
condition at the end of a loop. This is done by using
a do statement. The syntax of this statement is as
follows:
do{
program statements;
} while (expression) ;
10
• Here the program statements are first executed
once, then, the expression is evaluated. If it is
true, then it proceeds to the next iteration. This
continues till the expression evaluates to false.
• do-while loop behaves like a while-loop, except
that condition is tested after the execution of loop
body statements instead of before, guaranteeing at
least one execution of loop body statements, even
if condition is never fulfilled.

11
Example
do-while loop is frequently used where data is to
be read. The test then verifies the data, and loops
back to read again if it was unacceptable.
do{
cout << "Enter 1 for yes, 0 for no :";
cin >> myinput ;
} while (myinput != 1 && myinput != 0);

12
The following example will give the same results
when using do-while loop as the results obtained
using while loop.
void main ( )
{
int n = 10;
do {
cout << n << ", ";
--n;
} while (n>0);
cout << “Byebye\n";
}
13
The output of executing the program
will be as follows
• 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Byebye

14
• In the previous example if we initialize n by
negative value (-5 for example), the program
in case of do-while loop will print -5, Byebye
• This output is different than the output of the
while loop which will be just Byebye Without
printing any numbers.

15
The for Loop
• Often in programs we know how many times we
will need to repeat a loop. A while loop could be
used for this purpose by setting up a starting
condition; checking that a condition is true and
then incrementing or decrementing a counter
within the body of the loop. The for loop works
well (better) where the number of iterations of the
loop is known before the loop is entered. Its
syntax is:
• for (initialization; condition; increase)
{ loop body statements; }

16
The head of the loop consists of three
parts separated by semicolons.
• The first part run before the loop is entered. The
stating part can include an initialized control
variable.
• The second is a test, the loop is exited when this
returns false. The limiting condition tells the
program that while the conditional expression is
true the loop should continue to repeat itself.
• The third is a statement to be run every time the
loop body is completed. This is usually an
increment of the loop counter.
17
It works in the following way:
1. initialization is executed. Generally, this declares a
counter variable, and sets it to some initial value. This
is executed a single time, at the beginning of the loop.
2. condition is checked. If it is true, the loop continues;
otherwise, the loop ends, and statement is skipped,
going directly to step 5.
3. statement is executed. As usual, it can be either a
single statement or a block enclosed in curly braces {
}.
4. increase is executed, and the loop gets back to step 2.
5. the loop ends: execution continues by the next
statement after it.

18
Here is the countdown example using a
for loop:
int main ( )
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}
cout << “Byebye\n";
return 0;
}

19
• The three fields in a for-loop are optional. They
can be left empty, but in all cases the semicolon
signs between them are required. For example, for
(;n<10;) is a loop
without initialization or increase (equivalent to a
while-loop); and for (;n<10;++n)is a loop
with increase, but no initialization (maybe
because the variable was already initialized before
the loop). A loop with no condition is equivalent
to a loop with true as condition (i.e., an infinite
loop).

20
Nested loops
• Depending on the requirements of a program ,
you can have one for loop within another. This
is known as nesting of loops. In such a case the
complete inner loop is executed for every pass
of the outer loop. We can write any loop inside
any loop in c i.e. we can write for loop inside
the loop or while loop or do while loop etc.

21
Example of nested loop
We can use nested loops to print tables. As an example,
we want to write a program to print the following table:

A1 A2 A3 A4 A5
B1 B2 B3 B4 B5
C1 C2 C3 C4 C5
D1 D2 D3 D4 D5
E1 E2 E3 E4 E5
F1 F2 F3 F4 F5
G1 G2 G3 G4 G5
22
The program code will be as follows
int main(void) {
int num;
char ch;
for (ch = 'A'; ch <= 'G'; ch++)
{
for (num = 1; num <= 5; num++)
{
cout << ch << num << "\t";
}
cout << "\n";
}
return 0;
} 23
The break Statement
• We have already met break in the discussion of
the switch statement. It is used to exit from a
loop or a switch, control passing to the first
statement beyond the loop or a switch.
• In case of a nested loop, only the loop in
which the break statement occurs is
terminated.

24
• With loops, break can be used to force an early
exit from the loop, or to implement a loop with a
test to exit in the middle of the loop body. A break
within a loop should always be protected within
an if statement which provides the test to control
the exit condition.
• break leaves a loop, even if the condition for its
end is not fulfilled. It can be used to end an
infinite loop, or to force it to end before its natural
end.

25
For example, let's stop the countdown
before its natural end:
main ( )
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
}
26
The output will be as
• 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

27
The continue Statement
• Unlike a break statement, this causes the loop
in which it occurs to continue. It only works
within loops. All the statements following the
continue statement are ignored. This is used to
bypass a group of statements in a loop based
upon certain criteria or conditions. This
statement repeats the loop for next value (next
iteration). The statement “continue” transfers
the control back to the beginning of the loop
by ignoring set of statements written after it.
28
• Like a break, continue should be protected by
an if statement. You are unlikely to use it very
often.
• The continue statement causes the program to
skip the rest of the loop in the current iteration,
as if the end of the statement block had been
reached, causing it to jump to the start of the
following iteration.

29
Countdown example using continue to
skip printing number 5
int main ( )
{
for (int n=10 ; n > 0 ; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "liftoff!\n";
}
30
The output will be as follows
• 10, 9, 8, 7, 6, 4, 3, 2, 1, liftoff!

31
The goto statement
• C language includes the less
used goto statement. Same as the break and
continue statements, it is recommended to
avoid using this statement. A goto statement
causes a branch to be made to a specified point
in a program. This point is denoted by a label
which is a name followed by a colon. A label is
formed with the same rules as variable names.
This can be located anywhere in a program,
either before or after the goto statement.
32
• When the control reaches goto statement then
the execution is transferred from goto
statement to the statement preceded by the
label. Note that the symbol colon (:) is used
between the label and the statement.
• Note: Using too many goto statements in a
program reduces its readability and the
program becomes difficult to debug or
maintain.

33
The following example is a version of
our countdown loop using goto
int main ( )
{
int n = 10 ;
mylabel:
cout << n << ", ";
n--;
if (n>0) goto mylabel;
cout << "liftoff!\n";
}
34
The output of executing the program
will be as follows
• 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!

35
Problem 3.1
• Draw a flowchart and write a program to print
even numbers from 6 to 20
• We can write this program by 4 different
methods:
1. using goto statement,
2. using while loop,
3. using do-while loop,
4. using for loop.

36
37
//First solution: using goto statement
int main(void)
{
int num;
num = 6;
kkk:
cout << num << "\t";
num = num + 2;
if (num <= 20) goto kkk;
cout << "\n See you again \n";
return 0;
}

38
// Second solution: using while loop
int main(void)
{
int num;
num = 6;
while (num <= 20)
{
cout << num << "\t";
num = num + 2;
}
cout << "\n See you \n";
return 0;
}

39
//Third solution: using do-while loop
int main(void)
{
int num;
num = 6;
do{
cout << num << "\t";
num = num + 2;
} while (num <= 20);
cout << "\n See you \n";
return 0;
}
40
//Forth solution: using for loop
int main(void)
{
int num;
for(num = 6 ; num <= 20 ; num = num + 2)
{
cout << num << "\t";
}
cout << "\n See you \n";
return 0;
}
41
The output of running any of the previous four
solutions is the same. It will be as follow:
6 8 10 12 14 16 18 20
See you

42
Note
• Notice that there is no semicolon at the end of the
while or for statement. If we put semicolon at the
end of the while statement, the computer will
enter an infinite loop. If we put semicolon at the
end of the for loop statement, the computer will
consider the semicolon as the loop body. So the
computer will repeat do nothing inside the loop.
After finishing the loop, the computer will print
num only one time. Value of num is the value
which make the computer exit the loop which is
22 in this problem.

43
What is the output of executing this
program
int main(void)
{
int num;
for(num = 6 ; num <= 20 ; num = num + 2) ;
//WRONG semicolon
{
cout << num << "\t";
}
cout << "\n See you \n";
return 0;
}
44
Output
• The output of executing previous program will
be:
22
See you

45
Problem 3.2
• Draw a flowchart and write a program to add
the numbers from 1 to 10

46
47
int main(void)
{
int number, sum;
sum = 0;
for (number = 1; number <= 10; number++)
{
sum = sum + number;
}
cout << "Result of adding the numbers from 1
to 10 = " << sum << "\n";
return 0;
}

48
Output
Output of executing the previous program will
be as follow
Result of adding the numbers from 1 to 10 = 55

49
What about if we put by error a semicolon
after the for statement as follow
int main(void)
{
int number, sum;
sum = 0;
for (number = 1; number <= 10; number++) ; // Wrong
{ sum = sum + number; }
cout << "Result of adding the numbers from 1 to 10 = "
<< sum << "\n";
return 0;
}
50
Output
• The compiler will not give a syntax error message. The
computer will run the program, and give wrong result.
That is what we call logic error. The output will be as
follow
• Result of adding the numbers from 1 to 10 = 11
• Putting the semicolon after the for loop make the
computer consider that the loop will repeat doing only
the semicolon. So the computer will do nothing 10
times, and after finishing the loop, the computer will
add the value of number to sum only one time. At this
point, the value of number will be 11.

51
Problem 3.3
• Draw a flowchart and write a program to calculate
factorial n. Where 5! = 5*4*3*2*1
• In this Problem, we want to calculate factorial n,
we do not know what is the value of n. So, we
have to ask the user to enter value of n. In the
previous Problem, it is required to add the
numbers from 1 to 10, so no need to ask user to
enter any data.
• In the previous Problem, we want to add some
numbers, so we initialize the variable sum by 0. In
this Problem, we will multiply numbers, so we
will initialize the variable by 1.
52
53
int main(void)
{
int n, k, factorial;
cout << "Please enter value of n: ";
cin >> n;
factorial = 1;
for (k = n; k >= 1; k--)
{ factorial = factorial * k; }
cout << "Factorial " << n << " = " << factorial
<< "\n";
return 0;
}
54
Problem 3.4
• Show the output of executing this program if
the user enters 3. Notice that the programmer
add semicolon by mistake at the end of the for
statement.

55
int main(void)
{
int n, k, factorial;
cout << "Please enter value of n: ";
cin >> n;
factorial = 1;
for (k = n; k >= 1; k--);
{
factorial = factorial * k;
}
cout << "Factorial " << n << " = " << factorial <<
"\n";
return 0;
}

56
Answer
• The output will be as follow:
• Please enter value of n: 3
• Factorial 3 = 0

57
Problem 3.5
• Write a program to print Hello n times

58
void main(void)
{
int n , counter ;
cout << "Please enter an integer number and then
press Enter: ";
cin >> n ;
counter = 1 ;
do{
cout << "Hello ";
counter++ ;
}while(counter <= n) ;
cout << "\n Byebye \n" ;
getch();
}
59
Problem 3.6
• Write a program to print out the whole ASCII
table of characters using a for loop.

60
int main()
{
int number;
char character;
for (number=32; number<=126; number++)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
}
return 0;
}
61
Output
• The character ' ' is represented as the number
32 in the computer.
• The character '!' is represented as the number
33 in the computer.
• ...
• ...
• The character '}' is represented as the number
125 in the computer.
• The character '~' is represented as the
number 126 in the computer.

62
Problem 3.7
• Write a program to print n terms from this
series: 1, 1, 2, 3, 5, 8, 13, 21, …….. . Note that
the first and second term = 1, any other term
equals the sum of the previous two terms.

63
int main() {
int a, b, c, k, n;
cout << "Please enter value of n: ";
cin >> n;
a = 1; b = 1;
cout << a << "\t" << b << "\t";
for (k = 2; k <= n; k++)
{ c = a + b; cout << c << "\t";
a = b; b = c; }
return 0;
} 64
Problem 3.8
• Write a program to add positive numbers
entered by the user until the user enters a
negative number

65
int main(void)
{
int number, sum;
sum = 0;
do{
cout << "Please enter a number to add, or
negative number to stop: ";
cin >> number;
if(number > 0) sum = sum + number;
} while (number >= 0);
cout << "Sum = " << sum << "\n";
return 0;
}
66
The output of running this program if the user enters the
numbers:1,3,2,0,4,-2
Please enter a number to add, or negative number to stop: 1
Please enter a number to add, or negative number to stop: 3
Please enter a number to add, or negative number to stop: 2
Please enter a number to add, or negative number to stop: 0
Please enter a number to add, or negative number to stop: 4
Please enter a number to add, or negative number to stop: -2
Sum of the entered numbers = 10

67
Problem 3.9
• Write a program to add the numbers entered by
the user until the sum exceeds 100

68
int main(void)
{
int number, sum;
sum = 0;
while (sum <= 100)
{
cout << "Please enter a number to add: ";
cin >> number;
sum = sum + number;
}
cout << "Sum of the entered numbers = " << sum
<< "\n";
return 0;
}

69
Problem 3.10
• Write a program to read 10 numbers from the
user. The program prints how many of these
numbers are positive numbers and how many
are negative numbers. Consider zero as
neutral. So do not count zero as positive or
negative.

70
int main(void) {
int positive_counter, negative_counter, num, k;
positive_counter = negative_counter = 0;
for (k = 1; k <= 10; k++)
{
cout << "Please enter a number"<< k << " from 10 numbers:";
cin >> num;
if (num > 0) positive_counter++;
else if(num < 0) negative_counter++;
}
cout << "Number of positive= " << positive_counter << "\n";
cout << "Number of negative= " << negative_counter << "\n";
return 0;
}
71
Problem 3.11
• Write a program to read 10 numbers from the
user. The program will calculate and print the
average of odd numbers and the average of
even numbers.

72
int main(void)
{
int odd_sum, odd_counter, even_sum, even_counter, num, k;
float even_average, odd_average;
odd_sum = even_sum = odd_counter = even_counter = 0;
for (k = 1; k <= 10; k++)
{
cout << "Please enter a number " << k << " from 10
numbers: ";
cin >> num;
if (num % 2 == 0)
{ even_sum = even_sum + num; even_counter++; }
else { odd_sum = odd_sum + num;
odd_counter++; }
}

73
even_average = 1.0 * even_sum / even_counter;
odd_average = 1.0 * odd_sum / odd_counter;
cout << "Average of even numbers = " <<
even_average << "\n";
cout << "Average of odd numbers = " <<
odd_average << "\n";
return 0;
}
74
Problem 3.12
• Write a program to read 10 numbers from the
user. The program will print maximum number
and minimum number.

75
int main(void)
{
int maximum, minimum, num, k;
maximum = 0;
minimum = 1000000;
for (k = 1; k <= 10; k++)
{
cout << "Please enter number " << k << " from 10 numbers: ";
cin >> num;
if (num > maximum) maximum = num;
if (num < minimum) minimum = num;
}
cout << "Maximum number = " << maximum << "\n";
cout << "Minimum number = " << minimum << "\n";
return 0;
}

76
Problem 3.13
• Draw a flowchart and write a program to read
an integer positive number from the user. The
program will test and print if this number is a
prime number or not.

77
void main(void)
{
int num, flag;
cout << "Enter a positive integer number: ";
cin >> num;
flag = 0;
for (int k = 2; k <= num / 2; k++)
if (num % k == 0) { flag = 1; break; }
if (flag == 0) cout << num << " is prime number \n";
else cout << num << " is not a prime numbr \n";
return ;
}

78
Problem 3.14
• Draw a flowchart and write a program to read
an integer positive number which represents a
month number. Verify that the number is
between 1 and 12. If the user enters a wrong
number, repeat reading until entering correct
number. Print the corresponding season name
according to the following table
Month
12, 1, 2 3, 4, 5 6, 7, 8 9, 10, 11
number
Season name
Winter Spring Summer Fall
79
int main(void)
{
int month;
do{
cout << "Please enter month number: ";
cin >> month;
} while ((month < 1) || (month > 12));
if ((month == 12) || (month <= 2))
cout << "Season is Winter \n";
else if (month <= 5) cout << "Season is Spring \n";
else if (month <= 8) cout << "Season is Summer \n";
else if (month <= 11) cout << "Season is Fall \n";
return 0;
}

80
Problem 3.15
• Write a program to calculate factorial n. Verify
that n is a positive number less than 10. Re-ask
the user to enter another number if he enters a
wrong number.

81
int main(void)
{
int num , k , fact;
do{
cout << "Please enter a positive integer number less
than 10: ";
cin >> num;
} while ((num < 0) || (num >= 10));
fact = 1;
for (k = num; k >= 1; k--) fact = fact * k;
cout << "Factorial of " << num << " = " << fact << "\n";
return 0;
}

82
Problem 3.16
• Write a program to print 5 rows. Each row has
7#

83
int main(void)
{
int r, c;
for (r = 1; r <= 5; r++)
{
for (c = 1; c <= 7; c++) cout << " # ";
cout << "\n";
}
return 0;
}
84
Problem 3.17
• Write a program to print the numbers from 1 to
60 in 10 lines. Each line has 6 numbers.

85
int main(void)
{
int r, c, k;
k = 1;
for (r = 1; r <= 10; r++)
{
for (c = 1; c <= 6; c++)
cout << k++ << "\t";
cout << "\n";
}
return 0;
}
86
Another solution
int main(void)
{
int k;
for (k = 1; k <= 60; k++)
{
cout << k << "\t";
if (k % 6 == 0) cout << "\n";
}
return 0;
}

87
Problem 3.18
• Write a program to print all prime numbers
less than 1000

88
int main(void)
{
int num, k, flag;
for (num = 1; num <= 1000; num++)
{
flag = 0;
for (k = 2; k <= num / 2; k++)
if (num%k == 0) { flag++; break; }
if (flag == 0) cout << num << "\t";
}
return 0;
}
• 89
Problem 3.19
• Write a program to count how many prime
numbers from 2 to 100

90
int main(void)
{
int num, k, flag , counter;
counter = 0;
for (num = 2; num <= 100; num++)
{
flag = 0;
for (k = 2; k <= num / 2; k++)
if (num%k == 0) { flag++; break; }
if (flag == 0) counter++;
}
cout << "Number of prime numbers = " << counter << "\n";
return 0;
}

91
Problem 3.20
• Write a program to print the first 20 prime
numbers.

92
int main(void)
{
int num, k, flag, counter;
counter = 1;
for (num = 1; counter <= 20; num++)
{
flag = 0;
for (k = 2; k <= num / 2; k++)
if (num%k == 0) { flag++; break; }
if (flag == 0) { cout << num << "\t"; counter++; }
}
return 0;
}
93
Problem 3.21
• Write a program to simplify a / b. For example,
if the user enters 36 and 60, the program will
print that 36/60 equal to 3 / 5

94
int main(void)
{
int a, b, k;
cout << "Please enter two integer numbers: ";
cin >> a >> b;
cout << a << " / " << b;
k = 2;
while ((k <= a) && (k <= b))
{
if ((a%k == 0) && (b %k == 0))
{ a= a / k; b= b / k; cout <<"="<<a<<"/"<<b; }
else k++;
}
cout << "\n";
}
95
Problem 3.22
• Write a program to read many month numbers
and print the corresponding season for each
month number. In this program we do not
know how many months the user will enter.
So the program will ask the user if he wants to
repeat the program (if he wants to enter anther
month).

96
void main(void) {
int month ;
char select ;
do{
cout << "Enter the month number: " ;
cin >> month ;
if((month <= 0) || (month > 12)) cout << "Wrong number\n";
else if((month <= 2) || (month == 12)) cout<< "Winter \n";
else if(month <= 5) cout<< "Spring \n";
else if (month <= 8) cout<< "Summer\n";
else cout << "Fall \n";
cout << "Type y if you want to repeat or any other to end:";
cin >> select ;
}while((select == 'y') || (select == 'Y'));
97
}
Problem 3.23
• Write a program to read scores and print the
grades

98
void main(void)
{
float score ;
char select ;
do{
cout << "Enter the score: ";
cin >> score ;
if((score > 100) || (score < 0)) cout << "Wrong score\n" ;
else if(score >= 85) cout << "Ex \n" ;
else if(score >= 75) cout << "VG \n" ;
else if(score >= 65) cout << "GD \n" ;
else if(score >= 50) cout << "Ps \n" ;
else cout << "Fa \n" ;
cout << "Please type y if you want to repeat the program: ";
cin >> select ;
}while((select == 'y') || (select == 'Y'));
}

99
Problem 3.24
Write a program to print Hello n times using
1. Using do-while loop,
2. Using while loop.
Compare between the two solution.

100
1. Using do-while loop
void main(void)
{
int counter , n ;
cout << "Enter value of n: ";
cin >> n ;
counter = 1 ;
do{
cout << "Hello \t";
counter = counter + 1 ;
}while(counter <= n);
}
101
2. Using while loop
void main(void)
{
int counter , n ;
cout << "Enter value of n: ";
cin >> n ;
counter = 1 ;
while(counter <= n)
{
cout << "Hello \t";
counter = counter + 1 ;
}
} 102
Comparison
• The first program is not correct because if the user
enters 0 the program will print Hello 1 time. This
will be happen because the computer test the loop
condition at the end of the loop. So in case of do-
while loop the computer must execute the body of
the loop one time at least even if the looping
condition is not satisfied from the beginning. To
overcome this problem we can use while loop. In
case of while loop the looping condition is written
before the loop. So if the user enter zero the
computer will not print Hello at all. Note that we
could use for loop and the program will be good
also (as using while loop) as shown.
103
Using for loop
void main(void)
{
int counter , n ;
cout << "Enter value of n: ";
cin >> n ;
for(counter = 1 ; counter <= n ; counter++)
{ cout << "Hello \t"; }
}

104
Problem 3.25
Write a program to print this figure using nested
loop
*
**
***
****
*****
******
*******
105
void main(void)
{
int r , c ;
for(r = 1 ; r <= 7 ; r++)
{
for( c = 1 ; c <= r ; c++)
{ cout << " * " ; }
cout << "\n";
}
}
106
Problem 3.26
Write a program to print this figure using nested
loop
*******
******
*****
****
***
**
*

107
void main(void)
{
int r , c ;
for(r = 7 ; r >= 1 ; r--)
{
for( c = 1 ; c <= r ; c++)
{ cout << " * " ; }
cout << "\n";
}
}
108

You might also like