Chapter 3 Looping
Chapter 3 Looping
R
Looping
U
Cell Number: 0729 260 641
Email: [email protected]
Introduction
UL
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.
G
Objectives
By the end of this topic, you should be able to
Looping (Iteration/Repetition) in C
R
3.1 Introduction
The code below counts 1 → 5
U
1 #include<stdio.h>
2 int main()
3 {
4 printf (”%d \n”, 1);
5
6
7
8
9 }
printf (”%d \n”, 2);
printf (”%d \n”, 3);
printf (”%d \n”, 4);
printf (”%d \n”, 5);
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
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.
.
1. while loop - This loop executes a block of code until a certain condition is met.
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.
R
4 block to execute if condition is true
5 update control variable
6 }
U
Figure 3.1 shows the flowchart of a while loop execution
UL
G
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 {
printf (”%d \n”, count);
DR
4
5 count++;
6 }
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 }
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.
DR
The line
1 while ( count <= 5 )
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-
R
U
UL
G
Figure 3.3: while loop flow of execution
AN
6
7 while ( x > 0)
DR
8 {
9 factorial ∗= x; //same as factorial = factorial ∗ x
10 x−−; //same as x = x − 1, same as −−x, same as x −= 1
11 }
12 printf (”Factorial = %d”, factorial) ;
13 return 0;
14 }
R
13
U
1 #include<stdio.h>
2 int main()
3 {
4 int i = 2; //start counting from 2
5
6
7
8
9
10
11
}
UL
int sum = 0; // initially sum is zero
while ( i <= 10) //execute following block of code as long as i less of equal to 10
{
sum = sum + i; //add i to sum, store results in sum
i += 2; //increment i
OR
AN
1 #include<stdio.h>
2 int main()
3 {
4 int i = 2; //start counting from 2
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 += 2; //increment i
.
10 }
11 printf (”Sum = %d \n”, sum);
DR
12 return 0;
13 }
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
R
15 printf (”Square root of %lf = %lf ”, a, xn);
16
17 return 0;
18 }
U
5. Write a program that evaluates the following series
100
1
2
#include<stdio.h>
int main()
ULX
i=1
1
i2 1
1
2
1
3
1
= 2 + 2 + 2 ··· +
1
1002
3 {
4 int i = 1;
G
5 double sum = 0.0;
6 while ( i <= 100)
7 {
8 sum += 1.0 / (i ∗ i) ;
AN
9 i++;
10 }
11 printf (”Sum = %lf ”, sum);
12
13 return 0;
14 }
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 {
4 int n;
5 int f0 = 0;
6 int f1 = 1;
7 printf (”How many fibonacci numbers do you need? ”);
R
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);
U
14 f0 = f1;
15 f1 = next;
16 n−−; //update n
17 }
return 0;
18
19 }
UL
Listing 3.11: Fibonacci sequence of first N numbers (using while loop)
where i is the number of times you approximate e. Write a C program that display e for i =
AN
1, 2, 3, . . . 100.
Hint: Because i! = i × (i − 1) × (i − 2) · · · × 2 × 1, therefore,
1 1
=
i! i(i − 1)!
1 #include<stdio.h>
int main()
.
2
3 {
DR
4 double e = 1;
5 int fact = 1;
6 int i = 1;
7 while ( i <= 10)
8 {
9 int factorial = i ∗ fact ;
10 e += (1.0 / factorial ) ;
11 fact = factorial ;
12 i++;
13 }
14 printf (”e = %.5lf ”, e) ;
15 }
R
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.
1 int n = 1;
2 int stop;
U
3 scanf(”%d”, &stop);
4 while ( n <= stop)
5 {
6 printf (”%d ”, n);
n += 1;
7
8 }
A loop is indefinite if we cannot predict at any point during execution how many iterations (repetitions)
AN
9
10 if (entry == 999) //check if its equal to our magic number
DR
11 {
12 printf (”Done. You entered magic number\n”);
13 done = 1; //if user got magic number, stop repetition
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 loops 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
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.
An infinite loop occurs when the loop control condition is always true (will never be false). If you for-
R
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.
1 int n = 0;
2 int sum = 0;
U
3 while (n <= 10)
4 {
5 sum += n; //this line will execute forever , though theoretically
6 }
printf (”Sum = %d ”, sum); //this line will never execute
7
• initialization: count = 1
• Check: count <= 5
• Update: count += 1
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 {
.
This code behaves identically to the while loop in Listing 3.2. The printf(. . . ) statement here executes
exactly 5 times.
R
U
UL
Figure 3.4: for loop flow of execution
G
3.5.1 Some examples using for loop
1. Factorial of a number using for loop
AN
1 #include<stdio.h>
2 int main(){
3 int x;
4 printf (”Enter a number: ”);
5 scanf(”%d”, &x);
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
DR
13 return 0;
14 }
R
13
U
Fn = Fn−1 + Fn−2 for F0 = 0 and F1 = 1
using for loop, write a program that will read a number N and display N Fibonacci numbers.
1
2
3
4
5
6
#include<stdio.h>
int main()
{
int n;
int f0 = 0;
int f1 = 1;
UL
7 printf (”How many fibonacci numbers do you need? ”);
8 scanf(”%d”, &n);
G
9 printf (”%d %d”, f0, f1); //display first 2 numbers
10 for ( ; n − 2 > 0 ; n−−)
11 {
12 int next = f0 + f1;
AN
13 printf (” %d ”, next);
14 f0 = f1;
15 f1 = next;
16 }
17
18 return 0;
19 }
1 #include<stdio.h>
2 int main()
3 {
4 int i ;
5 double sum = 0.0;
6 for ( i = 1; i <= 100; i++)
7 {
8 sum += 1.0 / (i ∗ i) ;
R
9 }
10 printf (”Sum = %lf ”, sum);
11
12 return 0;
13 }
U
5. If xn is a close approximation to the square root of A then a better one is xn+1 given by
1 A
1
at N number of improvements.
#include<stdio.h>
ULxn+1 =
2
xn +
xn
using a for loop, write a program which reads some positive quantity A and calculates its square root
2 int main()
3 {
G
4 double a;
5 int n;
6 printf (”Enter a number: ”);
7 scanf(”%lf”, &a);
double xn = a / 2; // first guess (approximate) of square root
AN
8
9 printf (”Your guess is %lf \n”, xn);
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
16 }
17 printf (”Square root of %lf = %lf ”, a, xn);
18
.
19 return 0;
}
DR
20
R
Listing 3.24: Approximate e (exponential)
U
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.
1
UL
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least once.
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
them, however, can make programs difficult to read and debug.
You can also use break in a loop to immediately terminate the loop. Listing 3.26 presents a program to
R
demonstrate the effect of using break in a loop.
1 #include<stdio.h>
2 int main()
3 {
4 int number = 0;
U
5 int sum = 0;
6 while (number <= 20)
7 {
8 sum += number;
if (sum > 100)
9
10
11
12
13
14
15 }
}
break;
number++;
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
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;
DR
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
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.
R
3.8.1 Nested loops more examples - Triangles
1. Write a loop that draws a rectangle of asterisks with 7 rows 7 columns
* * * * * * *
* * * * * * *
* * * * * * *
U
* * * * * * *
* * * * * * *
* * * * * * *
1
2
3
4
5
* *
{
* * *
#include<stdio.h>
int main()
int rows = 0;
while(rows < 7)
* *
UL
6 {
G
7 int cols = 0;
8 while( cols < 7)
9 {
10 printf (” ∗ ”);
11 cols++;
AN
12 }
13 rows++;
14 printf (”\n”);
15 }
16 }
17 /∗equivalent code using for loops
18 for ( int rows = 0; rows < 7; rows++)
19 {
20 for ( int cols = 0; cols < 7; cols++)
21 {
.
22 printf (” ∗ ”);
23 }
DR
24 printf (”\n”);
25 }∗/
R
Listing 3.29: Triangle 1
U
* * * * *
* * * *
* * *
1
2
3
4
* *
*
#include<stdio.h>
int main()
{
int rows = 7;
UL
5 while(rows >= 0)
G
6 {
7 int cols = 0;
8 while( cols <= rows)
9 {
printf (” ∗ ”);
AN
10
11 cols++;
12 }
13 rows−−;
14 printf (”\n”);
15 }
16 }
17 //re−write this code using for loops
R
4
5 while(rows < 7)
6 {
7 int cols = 0;
8 while( cols < 7)
9 {
if (rows != 0 && cols < rows)
U
10
11 printf (” ”);
12 else
13 printf (” ∗ ”);
14 cols++;
15
16
17
18
19
20
}
}
}
rows++;
printf (”\n”); UL
//re−write this code using for loops
0 1 2 3 4 5 6
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
1 #include<stdio.h>
.
2 int main()
3 {
DR
4 int rows = 0;
5 while(rows < 7)
6 {
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 }
R
1 #include<stdio.h>
2 int main()
3 {
4 int rows = 7;
5 while(rows >= 0)
U
6 {
7 int cols = 0;
8 while( cols <= 7)
9 {
10
11
12
13
14
15
16
}
if (rows − cols >= 0)
printf (” ”);
else
printf (” ∗ ”);
cols += 1;
rows −= 1;
UL
17 printf (”\n”);
G
18 }
19 }//re−write the code using for loop
9 {
DR
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
R
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
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.
U
UL
G
. AN
DR