Intro C Prog 4
Intro C Prog 4
4. Loops
do, while and for Constructs
Yacoub Sabatin
1
Loops
• A loop is a statement whose job is to repeatedly
execute some other statements (loop body).
• Loops have:
– Controlling Expression
(condition)
– & Loop Body
1
4/6/2025
Loops
• C Supports: three types of loops:
– while, do while and for;
– All have:
• Controlling Expression &
• Loop Body
• while loop: Keeps repeating an action until an associated
test returns false;
– Useful where the programmer does not know in
advance how many times the loop will be traversed.
• do while loop: Similar to while, but the test occurs after
the loop body is executed.
– This ensures: loop body is run at least once.
•for loop: Frequently used, where the loop will be
traversed a fixed number of times.
3
while loop
• while loop is used to evaluate a block of code
(statements) as long as some condition is true. (while loop
repeated until condition becomes false)
– If the condition is false, from the start the block of
code is not executed at all.
– Syntax is as follows
while (tested condition is satisfied ){
statement
}
Controlling expression
• Psuedocode:
While there are more items on my shopping list
Purchase next item and cross it off my list
2
4/6/2025
• Consider:
int counter = 1; // initialization
while ( counter <= 10 ) // Repetition condition
{
printf(“ %d\n “, counter );
++counter;
} // increment
true
product <= 1000 product = 2 * product
false
int product = 2;
while ( product <= 1000 )
product = 2 * product;
5
•Example 1:
int number=99;
while (number != 999)
{
printf(\n Input Value=%d\n“, number);
scanf(“%d”, &number); //number is updated
}
• Example 2:
x = 0;
while (x < 100);
x++; // Infinite loop!
3
4/6/2025
4
4/6/2025
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
9
5
4/6/2025
• Algorithm:
1. Start;
2. Sum_Of_Integers = 0;
3. Read Integer;
4. while (Integer !=0){
Sum_Of_Integers = Sum_Of_Integers + Integer;
Read Integer;}
5. Output Sum_Of_Integers;
6. End.
11
• Code:
#include <stdio.h>
main()
{
int Integer, Sum_Of_Integers;
Sum_Of_Integers = 0;
printf(“\n Please enter an integer you
need”);
printf(“\n Please enter 0 to stop”);
scanf(“%d”, &Integer);
while (Integer !=0){
Sum_Of_Integers += Integer;
scanf(“%d”, &Integer);}
printf(“\n The sum of the entered
Integers=%5d”, Sum_Of_Integers);
return 0;
}
12
6
4/6/2025
13
7
4/6/2025
• Pseudo code:
Initialize passes to zero
Initialize failures to zero
Initialize student to one
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
16
8
4/6/2025
Do Loop
• do loop executes a block of code as long as a condition is
satisfied (true).
• The difference between a do & while loop is:
– while loop tests its condition at top of its loop;
i.e. if the test condition is false as the while loop is
entered the block of code is skipped.
– do loop tests its condition at bottom of its loop
i.e. Since the condition is tested at the bottom of a do
loop, its block of code is always executed at least once;
Syntax:
do {
block of code (statement);
} while ( condition / Expression is
satisfied);
17 C_Prog. Spring 2012
Do While Loop
action(s)
true
condition
false
18
9
4/6/2025
number = 44;
do {
Read guess;
i f ( g u e s s > n u m b e r ) { p r i n t f ( "T o o H i g h \ n ") ; }
i f ( g u e s s < n u m b e r ) { p r i n t f ( " T o o L o w \ n ") ; }
} while (guess != number)
Output number;
20
10
4/6/2025
#include <stdio.h>
#include <stdlib.h>
main()
{ int guess, number = 44
p r i n t f ( " Guess a number between 1 & 100\ n " ) ;
do {
printf("Enter your guess: ");
scanf("%d",&guess);
if (guess > number) {
printf("Too High\n"); }
if (guess < number) {
printf("Too Low\n"); }
} while (guess != number);
p r i n t f ("You win. The answer %d", n u m b e r );
return 0; }
• Note: The function rand() in stdlib.h can be used here instead, it returns
a random integer from 0 to RAND_MAX (defined in .h file usually 32767 or
2147483647)
• Can you think of more ideas? Print range? Levels? Points? Sounds? etc
21
22
11
4/6/2025
Introduction to computer
Engineering
Yacoub Sabatin
Tue 17-12-2024
Will start in a few moments..
24
12
4/6/2025
#include <stdio.h>
int main()
{
int digits=0; int number;
printf(“Enter a nonnegative integer.\n");
scanf(“%d”, &number);
do
{
number /= 10;
digits++;
} while (number>0);
26
13
4/6/2025
27
For loop
• for loop can execute a block of code for a fixed number of
repetitions.
• Best choice for loops that:
– count up (increment); OR,
– count down (decrement)
• for loop syntax is as follows:
for (initializations; test conditions;
operation)
{
block of code
} for (expression1; expression2;
expression3)
{
Statement
} 28
14
4/6/2025
Establish initial
value of control
variable
Prints the integers from one to ten
counter
counter= =1 1
true
counter <= 10 printf( "%d\n", counter ); counter++
Increment
the control
Determine if final false Body of loop variable
value of control (this may be many
variable has been statements)
reached
29
initialization;
while ( loopContinuationTest / expression2 ) {
statement;
increment;
}
int counter = 1;
while (counter <= 10 ) {
printf( "%d\n", counter );
counter++;
} // prints 1 to 10!
for(int counter = 1; counter <= 10; counter++)
printf( "%d\n", counter );
30
15
4/6/2025
Examples 1:
• Counting up from 0 to n-1:
for (count = 0; count < n; count++){
printf("%d\n",count); }
• Counting up from 1 to n:
for (count = 1; count <= n; count++){
printf("%d\n",count); }
• Counting down from n-1 to 0:
for(count = n-1; count >= 0; count--
){ printf("%d\n",count); }
• Counting down from n to 1:
for (count = n; count > 0; count--)
printf("%d\n",count);
• Note: not need for curly brackets in
31 1-line loop body.
Examples 2:
• A for loop that counts from 10 to 20:
for (count = 10; count <= 20; count++)
{
printf("%d\n", count);
}
• A loop that counts until a user response
terminates the loop:
for (count = 1; response != 'N'; count++)
{
printf("%d\n",count);
printf("Continue (Y/N): \n");
scanf("%c",&response);
}
32
16
4/6/2025
33
34
17
4/6/2025
36
18
4/6/2025
19
4/6/2025
Example:
/* Summation of even numbers with the for loop */
int sum = 0; /* initialize sum */
int number; /* number to be added to sum */
for (number = 2; number <= 100; number += 2)
{
sum += number; /* add number to sum */
} /* end for */
printf( "Sum = %d.\n", sum ); /* output sum */
40
20
4/6/2025
• Example:
FC Barcelona met Real Madrid FC 30 times, write a concise
and interactive C program that asks the user for the score of
each team in each of the 30 matches, calculates and prints the
points of each team, assuming 0 point for the loser, 1 point for
tie, and 2 points for the winner.
• Reasoning:
– Will use 2 variables to store scores and 2 variables to store
points
– Will use for loop structure to get the results of the 30
matches
– Will check the result of each match to determine how many
points would be added to each team.
• Code: Next slide:
41
#include <stdio.h>
void main()
{
int fcb_score, rmfc_score, fcb_points=0, rmfc_points=0;
for (int i=1; i <= 30; i++)
{
printf(“Please enter the score of FCB in match number: %d”, i);
scanf(“%d”, &fcb_score);
printf(“Please enter the score of RM FC in match number: %d”, i);
scanf(“%d”, &rmfc_score);
if (rmfc_score == fcb_score)
{
rmfc_points++;
fcb_points++;
}
else if (rmfc_score > fcb_score) //rmfc is the winner
rmfc_points = rmfc_points + 2;
else //fcb is the winner
fcb_points = fcb_points + 2;
} //end of ‘for’
21
4/6/2025
7 + 3, 6 * 2; /* Returns 12 */
3,14; /* Gives 14 (the rightmost expn and not 3.14) */
a = 0, b = 3, a += b, b = 0;
/* sets a to 3, b to 0 and returns 0 */
43
22
4/6/2025
Examples:
• Suppose i=1, j=5; when the expression ++i,i+j is
evaluated, i is first incremented, then i+j is evaluated,
the value of expression is 7 (and i is 2 now).
• We can write:
sum=0;
for (i=1 ; i<=N ; i++)
sum += i;
As:
for (sum=0, i=1 ; i<=N ; i++)
sum += i;
Or even:
for (sum=0, i=1 ; i<=N ; sum += i, i++);
45
46
23
4/6/2025
47
Example: Check whether Number is a prime: Use for loop that divides
Number by numbers (nums) between 2 and Number-1!
48
24
4/6/2025
•Continue Statement:
–Is valid only within loops;
–Terminates the current loop iteration, but not
the entire loop;
–In a for or while, continue causes the rest
of the body statement to be skipped.
–In a for statement, the update is done;
–In a do-while, the exit condition is tested, and
if true, the next loop iteration is begun.
49
Example:
for (x = 10; x > 0; x = x - 1)
{
if(x > 5) continue;
printf("x = %d\n",x);
// will print only numbers NOT > 5
} // Check!!
50
25
4/6/2025
52
26