Chapter 3 Looping
Chapter 3 Looping
l
ae
BCS 111 / BIT 112 – Fundamentals of Programming
ph
Name: Dr. Raphael Angulu
Cell Number: 0729 260 641
Email: [email protected]
Introduction Ra
In this topic, we will learn basics of computer system. We will define various terms used in computers and
look at history of computers, characteristics of computers and basic organization of a computer.
u
Objectives
By the end of this topic, you should be able to
l
1. Write programs for executing statements repeatedly using a while loop
gu
l
Looping (Iteration/Repetition) in C
ae
3.1 Introduction
ph
The code below counts 1 → 5
1 #include<stdio.h>
2 int main()
{
Ra
3
4 printf (”%d \n”, 1);
5 printf (”%d \n”, 2);
6 printf (”%d \n”, 3);
7 printf (”%d \n”, 4);
8 printf (”%d \n”, 5);
9 }
How would you write the code to count to 10,000? Would you copy, paste, and modify 10,000 printing
statements? You could, but that would be impractical! Counting is such a common activity, and computers
An
routinely count up to very large values, so there must be a better way. What we really would like to
do is print the value of a variable (call it count), then increment the variable (count += 1), and repeat
this process until the variable is large enough (count == 5 or maybe count == 10000). This process of
executing the same section of code over and over is known as iteration, or looping. C has three different
looping statements, while, for and do. . . while, that enable iteration.
Three types of loops in C
1. while loop - This loop executes a block of code until a certain condition is met.
.
Dr
Use a while loop when we want to execute a block of code as long as a certain condition
is met or until a certain condition is met.
2. for loop - This loop executes a block of code as long as there is an item in a control sequence
(list, tuple etc). This loop walks over a list, at each time initializing a loop control variable with
an element from the list, and execute its block of code as long as there is an element in the list.
Use a for loop when you know before hand how many times do you want to execute a
block of code.
2 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
3. do. . . while loop - This loop executes a block of code once then checks a condition and continue
(repeat) to execute the block of code as long as the condition is true.
l
1 initialize control variable ;
ae
2 while( condition )
3 {
4 block to execute if condition is true
5 update control variable
6 }
ph
Listing 3.1: while loop syntax (General structure)
Ra
l u
gu
An
For example, writing a piece of code above using while loop such that it prints 1 → 5
1 int count = 1;
2 while ( count <= 5 )
3 {
4 printf (”%d \n”, count);
5 count++;
}
.
6
Dr
Figure 3.2 shows the flow of execution of the code in Listing 3.2
The while statement in program above repeatedly displays the variable count. The program executes the
following block of statements five times:
1 {
2 printf (”%d \n”, count);
3 count++;
4 }
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 3
l
ae
ph
Ra
l u
gu
An
After each display of the variable count, the program increments it by one. Eventually (after five iterations),
the condition count <= 5 will no longer be true, and the block is no longer executed.
.
The line
Dr
begins the while statement. The expression following the while keyword is the condition that determines
if the statement block is executed or continues to execute. As long as the condition is true, the program
executes the code block over and over again. When the condition becomes false, the loop is finished. If
the condition is false initially, the program will not execute the code block within the body of the loop at all.
The executing program checks the condition before executing the while block and then checks the con-
4 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
dition again after executing the while block. As long as the condition remains true, the program repeatedly
executes the code in the while block. If the condition initially is false, the program will not execute the code
within the while block. If the condition initially is true, the program executes the block repeatedly until the
condition becomes false, at which point the loop terminates.
l
ae
ph
Ra
l u
Figure 3.3: while loop flow of execution
gu
1 #include<stdio.h>
2 int main()
3 {
4 int x;
5 scanf(”%d”, &x);
6 int factorial = 1;
7 while ( x > 0)
8 {
9 factorial ∗= x; //same as factorial = factorial ∗ x
.
11
12 printf (”Factorial = %d”, factorial) ;
13 return 0;
14 }
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 5
2. Program to calculate the sum of numbers between 0 and 10
1 #include<stdio.h>
2 int main()
3 {
4 int i = 0; //start counting from 0
5 int sum = 0; // initially sum is zero
6 while ( i <= 10) //execute following block of code as long as i less of equal to 10
7 {
8 sum = sum + i; //add i to sum, store results in sum
9 i += 1; //increment i
l
10 }
ae
11 printf (”Sum = %d \n”, sum);
12 return 0;
13 }
ph
3. Program to calculate the sum of even numbers between 0 and 10
1 #include<stdio.h>
2 int main()
3 {
4
5
6
7
8
9
10
int i = 2; //start counting from 2
int sum = 0; // initially sum is zero
}
sum = sum + i; //add i to sum, store results in sum
i += 2; //increment i
Ra
while ( i <= 10) //execute following block of code as long as i less of equal to 10
OR
1 #include<stdio.h>
2 int main()
3 {
An
4. If xn is a close approximation to the square root of A then a better one is xn+1 given by
1 A
xn+1 = xn +
2 xn
Write a program which reads some positive quantity A and calculates its square root to an accuracy
which ensures that the result squared and A differ by at most 10−6
6 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
1 #include<stdio.h>
2 int main()
3 {
4 double a;
5 printf (”Enter a number: ”);
6 scanf(”%lf”, &a);
7 double xn = a / 2; // first guess (approximate) of square root
8 double error = a − (xn ∗ xn); //calculate initial error
9 while (error > 0.000001 || error < −0.000001)
10 {
double xn1 = 0.5 ∗ (xn + (a / xn)); //lets calculate a better approximate
l
11
12 xn = xn1; //make our better to be our approximate
ae
13 error = a − (xn ∗ xn); //update error
14 }
15 printf (”Square root of %lf = %lf ”, a, xn);
16
17 return 0;
ph
18 }
1 #include<stdio.h>
100
X
i=1
1
i2 1
1
2
1
3
1
Ra
= 2 + 2 + 2 ··· +
1
1002
2 int main()
{
u
3
4 int i = 1;
5 double sum = 0.0;
while ( i <= 100)
l
6
7 {
gu
8 sum += 1.0 / (i ∗ i) ;
9 i++;
10 }
11 printf (”Sum = %lf ”, sum);
12
13 return 0;
An
14 }
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 7
6. The nth number in Fibonacci sequence is given by
write a program that will read a number N from the keyboard and display N Fibonacci numbers.
1 #include<stdio.h>
2 int main()
3 {
el
4 int n;
5 int f0 = 0;
6 int f1 = 1;
7 printf (”How many fibonacci numbers do you need? ”);
ha
8 scanf(”%d”, &n);
9 printf (”%d %d”, f0, f1); //display first 2 numbers
10 while ( n − 2 > 0 )
11 {
12 int next = f0 + f1;
13 printf (” %d ”, next);
p
14 f0 = f1;
15 f1 = next;
16 n−−; //update n
17
18
19 }
}
return 0;
Ra
Listing 3.11: Fibonacci sequence of first N numbers (using while loop)
1! 2! 3! 4! i!
where i is the number of times you approximate e. Write a C program that display e for i =
1, 2, 3, . . . 100.
ng
1 1
=
i! i(i − 1)!
.A
1 #include<stdio.h>
2 int main()
3 {
4 double e = 1;
5 int fact = 1;
6 int i = 1;
Dr
8 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
3.3 Definite Loops vs. Indefinite Loops
A loop is definite if we can predict how many times the loop will execute. Consider the code in Listing 3.13
which prints integers from 1 to 10
1 int n = 1;
2 while (n <= 10)
3 {
4 printf (”%d ”, n);
5 n++;
}
l
6
ae
Listing 3.13: Definite loop 1
We can inspect the code and determine the exact number of iterations the loop will perform. This kind of
loop is known as a definite loop, since we can predict exactly how many times the loop repeats. Consider
Listing 3.14.
ph
1 int n = 1;
2 int stop;
3 scanf(”%d”, &stop);
4 while ( n <= stop)
5 {
6
7
8 }
printf (”%d ”, n);
n += 1;
A loop is indefinite if we cannot predict at any point during execution how many iterations (repetitions)
the loop will perform. Consider the code in Listing 3.15
1 #include<stdio.h>
2 int main()
{
An
3
4 int done = 0; //enter loop atleast once
5 while (! done)
6 {
7 int entry;
8 printf (”Enter a Magic Number: ”);
9 scanf(”%d”, &entry); //read number from user
10 if (entry == 999) //check if its equal to our magic number
11 {
12 printf (”Done. You entered magic number\n”);
.
14 }
15 else
16 printf (”Failed . Try again\n”); //if not, continue asking for a number
17 }
18
19 return 0;
20 }
In Listing 3.15, we cannot predict at any point during the loop’s execution how many iterations the loop
will perform. The value to match (999) is known before and during the loop, but the variable entry can
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 9
be anything the user enters. The user could choose to enter 0 exclusively or enter 999 immediately and be
done with it. The while statement in Listing 3.15 is an example of an indefinite loop.
The while statement is ideal for indefinite loops. Although we have used the while statement to imple-
ment definite loops, C provides a better alternative for definite loops: the for statement.
l
An infinite loop is a loop that will theoretically execute forever.
ae
An infinite loop occurs when the loop control condition is always true (will never be false). If you for-
get to update a control variable in a while loop, you will definitely end up with an infinite loop – a loop that
will never stop execution, though theoretically. Example code in Listing 3.17 shows an example of infinite
loop.
ph
1 int n = 0;
2 int sum = 0;
3 while (n <= 10)
4 {
5 sum += n; //this line will execute forever , though theoretically
6
7
}
printf (”Sum = %d ”, sum); //this line will never execute
• initialization: count = 1
• Check: count <= 5
• Update: count += 1
An
C provides a more convenient way to express a definite loop. The for statement iterates over a sequence of
values as
1 for ( int i = 1; i <= 5; i++)
2 {
3 printf (”%d\n”, i);
4 }
This code behaves identically to the while loop in Listing 3.2. The printf(. . . ) statement here executes
exactly 5 times.
10 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
Figure 3.4 shows the flow of execution of a for loop.
l
ae
ph
Ra
Figure 3.4: for loop flow of execution
u
3.5.1 Some examples using for loop
l
1 #include<stdio.h>
2 int main(){
3 int x;
4 printf (”Enter a number: ”);
5 scanf(”%d”, &x);
An
6 int factorial = 1;
7 for ( int i = x; i > 0; i−−)
8 {
9 factorial ∗= i;
10 }
11 printf (”Factorial of %d is %d”, x, factorial ) ;
12
13 return 0;
14 }
.
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 11
2. Write a program to calculate sum of numbers between 0 and 10
1 #include<stdio.h>
2 int main()
3 {
4 int sum = 0;
5 int i ;
6 for ( i = 0; i <= 10; i++)
7 {
8 sum = sum + i;
9 }
l
10 printf (”Sum = %d ”, sum);
ae
11
12 return 0;
13 }
ph
3. The nth number in Fibonacci sequence is given by
1
2
3
4
5
int main()
{
int n;
int f0 = 0;
Ra
using for loop, write a program that will read a number N and display N Fibonacci numbers.
#include<stdio.h>
6 int f1 = 1;
printf (”How many fibonacci numbers do you need? ”);
u
7
8 scanf(”%d”, &n);
9 printf (”%d %d”, f0, f1); //display first 2 numbers
for ( ; n − 2 > 0 ; n−−)
l
10
11 {
gu
18 return 0;
19 }
12 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
4. Using for loop, write a program that evaluates the following series
100
X 1 1 1 1 1
2
= 2 + 2 + 2 ··· +
i 1 2 3 1002
i=1
1 #include<stdio.h>
2 int main()
3 {
4 int i ;
5 double sum = 0.0;
el
6 for ( i = 1; i <= 100; i++)
7 {
8 sum += 1.0 / (i ∗ i) ;
}
ha
9
10 printf (”Sum = %lf ”, sum);
11
12 return 0;
13 }
p
5. If xn is a close approximation to the square root of A then a better one is xn+1 given by
1
xn+1 =
1
2
xn +
A
xn
Ra
using a for loop, write a program which reads some positive quantity A and calculates its square root
at N number of improvements.
#include<stdio.h>
2 int main()
u
3 {
4 double a;
5 int n;
ul
10 printf (”How many times do you want to improve your guess? ”);
11 scanf(”%d”, &n);
12 for ( ; n > 0; n −= 1)
13 {
14 double xn1 = 0.5 ∗ (xn + (a / xn)); //lets calculate a better approximate
15 xn = xn1; //lets update our guess with a better approximate
.A
16 }
17 printf (”Square root of %lf = %lf ”, a, xn);
18
19 return 0;
20 }
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 13
1 #include<stdio.h>
2 int main()
3 {
4 double e = 2;
5 int fact 0 = 1;
6 for ( int i = 2; i <= 10; i++)
7 {
8 int factorial = i ∗ fact 0 ;
9 e += (1.0 / factorial ) ;
10 fact 0 = factorial ;
l
11 }
12 printf (”e = %.5lf ”, e) ;
ae
13 }
ph
3.6 do. . . while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks
its condition at the bottom of the loop.
Ra
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least once.
14 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
3.7 break and continue keywords
The break and continue keywords provide additional controls in a loop.
Two keywords, break and continue, can be used in loop statements to provide additional controls.
Using break and continue can simplify programming in some cases. Overusing or improperly using
l
them, however, can make programs difficult to read and debug.
ae
You can also use break in a loop to immediately terminate the loop. Listing 3.26 presents a program to
demonstrate the effect of using break in a loop.
1 #include<stdio.h>
ph
2 int main()
3 {
4 int number = 0;
5 int sum = 0;
6 while (number <= 20)
7 {
8
9
10
11
12
13
14
}
sum += number;
if (sum > 100)
break;
number++;
The program in Listing 3.26 adds integers from 1 to 20 in this order to sum until sum is greater than or
l
equal to 100. Without the if statement (line 9), the program calculates the sum of the numbers from 1 to
gu
20. But with the if statement, the loop terminates when sum becomes greater than or equal to 100.
You can also use the continue keyword in a loop. When it is encountered, it ends the current iteration
and program control goes to the end of the loop body. In other words, continue breaks out of an iteration
An
while the continue keyword breaks out of a loop. Listing 3.27 presents a program to demonstrate the effect
of using continue in a loop
1 #include<stdio.h>
2 int main()
3 {
4 int number = 0;
5 int sum = 0;
6 while (number <= 20)
7 {
.
8 sum += number;
Dr
9 number++;
10 if (number == 10)
11 continue;
12 }
13 printf (”Number = %d\n”, number);
14 printf (”Sum = %d\n”, sum);
15 }
The program in Listing 3.27 adds integers from 1 to 20 except 10 to sum. With the if statement in the
program (line 10), the continue statement is executed when number becomes 10. The continue statement
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 15
ends the current iteration so that the rest of the statement in the loop body is not executed; therefore,
number is not added to sum when it is 10.
You can always write a program without using break or continue in a loop. In general, though, using
break and continue is appropriate if it simplifies coding and makes programs easier to read.
el
Just like with if statements, while and for blocks can contain arbitrary C++ statements, including other
loops. A loop can therefore be nested within another loop.
ha
3.8.1 Nested loops more examples - Triangles
1. Write a loop that draws a rectangle of asterisks with 7 rows 7 columns
* * * * * * *
* * * * * * *
p
* * * * * * *
* * * * * * *
* * * * * * *
1
2
3
4
* *
* *
* * *
* * *
#include<stdio.h>
int main()
{
int rows = 0;
* *
* *
Ra
5 while(rows < 7)
u
6 {
7 int cols = 0;
8 while( cols < 7)
ul
9 {
10 printf (” ∗ ”);
11 cols++;
12 }
rows++;
ng
13
14 printf (”\n”);
15 }
16 }
17 /∗equivalent code using for loops
18 for ( int rows = 0; rows < 7; rows++)
.A
19 {
20 for ( int cols = 0; cols < 7; cols++)
21 {
22 printf (” ∗ ”);
23 }
24 printf (”\n”);
25 }∗/
Dr
16 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
1 #include<stdio.h>
2 int main()
3 {
4 for ( int rows = 0; rows < 7; rows++)
5 {
6 for ( int cols = 0; cols <= rows; cols++)
7 {
8 printf (” ∗ ”);
9 }
10 printf (”\n”);
l
11 }
12 }
ae
13 //re−write the code using a while loop
ph
3. Write a loop that draws a triangle of asterisks shown below
* * * * * * *
* * * * * *
* * * * *
* * * *
1
2
3
* *
* *
*
*
#include<stdio.h>
int main()
{
Ra
4 int rows = 7;
u
5 while(rows >= 0)
6 {
7 int cols = 0;
l
8 while( cols <= rows)
{
gu
9
10 printf (” ∗ ”);
11 cols++;
12 }
13 rows−−;
14 printf (”\n”);
An
15 }
16 }
17 //re−write this code using for loops
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 17
4. Write a loop that draws a triangle below
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
l
1 #include<stdio.h>
ae
2 int main()
3 {
4 int rows = 0;
5 while(rows < 7)
6 {
ph
7 int cols = 0;
8 while( cols < 7)
9 {
10 if (rows != 0 && cols < rows)
11 printf (” ”);
12 else
printf (” ∗ ”);
Ra
13
14 cols++;
15 }
16 rows++;
17 printf (”\n”);
18 }
19 }
20 //re−write this code using for loops
u
Listing 3.31: Triangle 3
l
gu
4 5 6
5 6
6
1 #include<stdio.h>
2 int main()
3 {
4 int rows = 0;
5 while(rows < 7)
.
6 {
Dr
7 int cols = 0;
8 while( cols < 7)
9 {
10 if (rows != 0 && cols < rows)
11 printf (” ”);
12 else
13 printf (” %d ”, cols) ; //we changed only this line from the code above!
14 cols++;
15 }
16 rows++;
17 printf (”\n”);
18 }
18 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping
19 }//re−write this code using for loops
l
* * * * *
ae
* * * * * *
* * * * * * *
1 #include<stdio.h>
2 int main()
ph
3 {
4 int rows = 7;
5 while(rows >= 0)
6 {
7 int cols = 0;
8 while( cols <= 7)
9
10
11
12
13
14
15
{
}
if (rows − cols >= 0)
printf (” ”);
else
printf (” ∗ ”);
cols += 1;
Ra
16 rows −= 1;
u
17 printf (”\n”);
18 }
19 }//re−write the code using for loop
l
3 {
4 int rows = 7;
5 while(rows >= 0)
6 {
7 int cols = 0;
8 while( cols <= 7)
9 {
10 if (rows − cols >= 0)
11 printf (” ”);
.
12 else
printf (” %d ”, cols) ; //we just changed this line from the code above
Dr
13
14 cols += 1;
15 }
16 rows −= 1;
17 printf (”\n”);
18 }
19 }
20 //re−write the code using for loop
Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 19
Assignment
1. A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors,
excluding itself. For example, 6 is the first perfect number because 6 = 3 + 2 + 1. The next is 28
= 14 + 7 + 4 + 2 + 1. There are four perfect numbers less than 10,000. Write a program to find
all these four numbers.
2. Given that days of the week are numbered as 1 = Monday, 2 = Tuesday, 3 = Wednesday . . . 7 =
Sunday, the formulae
l
d = R (1 + 5 (R(year − 1, 4)) + 4 (R(year − 1, 100)) + 6 (R(year − 1, 400)) , 7)
ae
where R(x,y) returns remainder after dividing x and y
returns the number representing the day of the week on which first of January falls. Write a Program
ph
that receives a year from the user (as a four digit number), and displays on which days will first of
January fall for 5 years from the year entered.
Ra
l u
gu
. An
Dr
20 Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping