0% found this document useful (0 votes)
79 views

Chapter 3 Looping

1. The document discusses looping in C programming using while, for, and do-while loops. It explains the basic syntax and flow of each loop type. 2. Examples are provided to illustrate using while loops to count from 1 to 5, calculate the factorial of a number, and calculate the sum of numbers between 0 and 10. 3. The key aspects of a while loop are initializing a control variable, specifying a condition to be checked, executing a block of code as long as the condition is true, and updating the control variable.

Uploaded by

Muli Analyst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Chapter 3 Looping

1. The document discusses looping in C programming using while, for, and do-while loops. It explains the basic syntax and flow of each loop type. 2. Examples are provided to illustrate using while loops to count from 1 to 5, calculate the factorial of a number, and calculate the sum of numbers between 0 and 10. 3. The key aspects of a while loop are initializing a control variable, specifying a condition to be checked, executing a block of code as long as the condition is true, and updating the control variable.

Uploaded by

Muli Analyst
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

School of Computing and Informatics

l
ae
BCS 111 / BIT 112 – Fundamentals of Programming

Lecturer Contact (name, telephone, e-mail)

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

2. Control a loop with a sentinel value (control variable)

3. Write loops using for loop

4. Write loops using do. . . while loop


An

5. Write nested loops

6. Implement program control with break and continue keywords


.
Dr
Chapter 3

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 }

The output of this code is


l u
gu

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.

3.2 while loop


As stated above, while loop executes a block of code until a certain condition is met. The general syntax of
a while loop is

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)

Figure 3.1 shows the flowchart of a while loop execution

Ra
l u
gu
An

Figure 3.1: while flowchart

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

Listing 3.2: while loop to count 1 → 5

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 }

Listing 3.3: Body of while loop

Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 3
l
ae
ph
Ra
l u
gu
An

Figure 3.2: Flow of execution of code that counts 1 → 5

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

1 while ( count <= 5 )

Listing 3.4: Loop control condition

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.

Figure 3.3 shows the flow of execution for a while loop.

l
ae
ph
Ra
l u
Figure 3.3: while loop flow of execution
gu

3.2.1 Some examples using while


1. Program that reads an integer from the user, calculates and display factorial of that integer.
An

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
.

10 x−−; //same as x = x − 1, same as −−x, same as x −= 1


}
Dr

11
12 printf (”Factorial = %d”, factorial) ;
13 return 0;
14 }

Listing 3.5: Factorial of a number

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 }

Listing 3.6: Sum of numbers between 0 and 10

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

11 printf (”Sum = %d \n”, sum);


u
12 return 0;
13 }

Listing 3.7: Sum of even numbers between 0 and 10


l
gu

OR
1 #include<stdio.h>
2 int main()
3 {
An

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);
12 return 0;
13 }
.

Listing 3.8: Sum of even numbers between 0 and 10


Dr

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 }

Listing 3.9: Calculate squareroot of number using Newtons algorithm

5. Write a program that evaluates the following series

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 }

Listing 3.10: Program that implements the equation above


.
Dr

Dr. Raphael Angulu, BCS 111 / BIT 112 SCI, MMUST, 2022: Chapter 3: Looping 7
6. The nth number in Fibonacci sequence is given by

Fn = Fn−1 + Fn−2 for F0 = 0 and F1 = 1

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)

7. You can approximate e using the series


u
1 1 1 1 1
e=1+ + + + ··· +
ul

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

Hint: Because i! = i × (i − 1) × (i − 2) · · · × 2 × 1, therefore,

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

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 }

Listing 3.12: Approximate e (using while loop)

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;

Listing 3.14: Definite loop 2 Ra


Looking at the source code of Listing 3.14, we cannot predict how many times the loop will repeat. The
number of iterations depends on the input provided by the user. However, at the program’s point of execu-
u
tion after obtaining the user’s input and before the start of the execution of the loop, we would be able to
determine the number of iterations the while loop would perform. Because of this, the loop in Listing 3.14
is considered to be a definite loop as well.
l
gu

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”);
.

13 done = 1; //if user got magic number, stop repetition


Dr

14 }
15 else
16 printf (”Failed . Try again\n”); //if not, continue asking for a number
17 }
18
19 return 0;
20 }

Listing 3.15: Indefinite loop

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.

3.4 Infinite loops

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

Listing 3.16: Infinite loop

3.5 for loop


Ra
u
The while loop is ideal for indefinite loops. A programmer cannot always predict how many times a while
loop will execute. We have used a while loop to implement a definite loop, as in Listing 3.2. The print
l
statement in this code executes exactly 5 times every time this code runs. This code requires three crucial
pieces to manage the loop:
gu

• 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 }

Listing 3.17: Counting using for loop


.
Dr

This code behaves identically to the while loop in Listing 3.2. The printf(. . . ) statement here executes
exactly 5 times.

The general structure of a for loop is


1 for ( initialization ; condition; update)
2 {
3 block of code to execute if condition is true
4 }

Listing 3.18: Genral Structure of for loop

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. Factorial of a number using for loop


gu

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 }
.

Listing 3.19: Factorial of a number using for loop


Dr

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 }

Listing 3.20: Sum of numbers 0 to 10 using for loop

ph
3. The nth number in Fibonacci sequence is given by

Fn = Fn−1 + Fn−2 for F0 = 0 and F1 = 1

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

12 int next = f0 + f1;


13 printf (” %d ”, next);
14 f0 = f1;
15 f1 = next;
16 }
17
An

18 return 0;
19 }

Listing 3.21: Fibonacci sequence of first N numbers using for loop


.
Dr

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 }

Listing 3.22: Program that implements the equation above

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

6 printf (”Enter a number: ”);


7 scanf(”%lf”, &a);
8 double xn = a / 2; // first guess (approximate) of square root
9 printf (”Your guess is %lf \n”, xn);
ng

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 }

Listing 3.23: Newton square root for loop


Dr

6. You can approximate e using the series


1 1 1 1 1
e=1+ + + + ··· +
1! 2! 3! 4! i!
where i is the number of times you approximate e. Write a C program that display e after approxi-
mating it 10 times.
Hint: Because i! = i × (i − 1) × (i − 2) · · · × 2 × 1, therefore,
1 1
=
i! i(i − 1)!

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 }

Listing 3.24: Approximate e (exponential)

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.

The general structure of a do...while loop is


1 do
{
u
2
3 code to execute
4 }
while( condition ) ;
l
5
gu

Listing 3.25: do...while loop general structure

Figure 3.5 shows the flow of execution of a do...while loop


. An
Dr

Figure 3.5: do...while loop flow of execution

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.

break and continue keywords

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++;

printf (”Number = %d\n”, number);


printf (”Sum = %d\n”, sum);
Ra
15 }
u
Listing 3.26: Terminate loop when sum reaches 100

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 }

Listing 3.27: Terminate loop when sum reaches 100

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.

3.8 Nested loops

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

Listing 3.28: Rectangle 1

2. Write a loop that displays the triangle below


*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *

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

Listing 3.29: Triangle 1

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

Listing 3.30: Triangle 2


.
Dr

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

5. Write a loop that draws a triangle below


0 1 2 3 4 5 6
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
An

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

Listing 3.32: Triangle 3

6. Write a loop that draws a triangle below


*
* *
* * *
* * * *

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

Listing 3.33: Triangle 4


gu

7. What will this code display


1 #include<stdio.h>
2 int main()
An

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

Listing 3.34: Triangle 6

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

You might also like