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

Chap4-Loop Statements

The document provides an overview of loop statements in programming, specifically focusing on their definition, types, and advantages. It explains three main types of loops: For, While, and Do..While, along with their syntax and usage in C language. Additionally, it includes exercises and solutions to reinforce the understanding of loop concepts.

Uploaded by

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

Chap4-Loop Statements

The document provides an overview of loop statements in programming, specifically focusing on their definition, types, and advantages. It explains three main types of loops: For, While, and Do..While, along with their syntax and usage in C language. Additionally, it includes exercises and solutions to reinforce the understanding of loop concepts.

Uploaded by

mr sebaagamer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Yahia Fares University of Médéa

Faculty of Sciences
Department of Mathematics and Computer Science
Year: 1st Year Computer Science Licence Degree
(L.M.D)

Algorithms and Data structure 1

2024-2025

1
Chapter IV

Loop Statements

2
Objective
• Understand the need to use repetitive statement
• Learn the different loop statements
• Analyze problems and write algorithms using loop
statement
• Write programs in C language using loop statement

3
Definition
The Loop statement is a control flow statement that execute one or more
instructions , called loop’s body, repeatedly multiple times.

The execution of the loop is controlled by a condition, which is evaluated at the


beginning or end of each iteration.

Why using the loop ?

• When you need to execute a block of code multiple times then you need to use
looping concept
4
Principle
The Condition is evaluated :

✓ If it is True then the instructions of Instructions block


to execute
block (loop body) will be executed
If condition is True
again and again. Condition

✓ if it becomes False, the loop will


terminate and then jump to the If condition is False
instruction after.
5
Advantage of loop statement

• Reduce the code’s length

• Take less memory space.

• Burden on the developer is reduced.

• The program execution process takes less time.

6
Types of Loops
We introduce 3 kinds of loop statements which belong to 2 main types :

❑ Pre-test loops: the condition is evaluated before the loop body is executed. If the
condition is false, the loop terminates without executing the loop body.

1. While

2. For

❑ Post-test loops: the condition is evaluated after the loop body is executed. If the
condition is false, the loop terminates.

3. Do .. While 7
Usage of loop statement
Usage of a loop type depends on knowing in advance the repeat count

Repeat count is known

While and Do while also can be used

Two cases For

Repeat count is unknown

While Do.. While


8
1.For loop

9
1. For loop
• Repeat count is known in advance: In this structure, the exit
from the iteration loop occurs when the desired repeat
count is reached.
Syntax : Initialization

For Index  Initial_value To Final_value Step n do


Action ;

positive or negative
integer
10
1. For loop

• If Action consists of multiple instructions, they must be put in block


delimited by Begin and End.

• If Initial value < Final value, then the loop is called ‘Ascending,' and the
iteration step will be positive (n>0)

• If Initial value > Final value, then it is called ‘Descending,' and the iteration
step will be negative (n<0)

11
1. For loop

❑ For each index variable (or iterator) value that varies from the initial value
to the final value the block will be executed.
❑ Each execution of the block is called an iteration.
❑ initialization of the index variable is done first
❑ In each iteration the loop performs :
✓ Execution of the instructions block
✓ Increment (n>0) or decrement (n<0) of the index

12
1. For loop
Examples
//ascending loop
For i  0 To 10 Step 2 Do
Write (i) ; Result : 0 2 4 6 8 10

//descending loop
For j  10 To 1 Step -1 Do
Write (j); Result : 10 9 8 7 6 5 4 3 2 1

//block execution
For k  0 To 20 Step 5 Do
Begin
Write (k);
Result : 0 0 5 50 10 100 15 150 20 200
Write(k*10);
13
end;
1. For loop

• In case where the step is 1 (n=1), the general form of the For loop will
be:
For Index  Initial_value To Final_value do
Action ;

Example
For i  1 To 10 Do
Write (i) ; Result : 1 2 3 4 5 6 7 8 9 10

14
2.While loop

15
2.While loop

Syntax: While condition Do


Action ; False True
Condition

Action
First check the condition, if condition is true then
control goes inside the loop body. Otherwise goes
outside the loop body. Loop Update

16
2.While loop

• Note1 : If Action consists of multiple instructions Condition


(2 or more), then must be put in a block delimited False True
Condition
by Begin and End

• Note2: The body of the While loop may never be Action


executed. So, this structure actually allows
repeating a process 0, 1, or multiple times Loop Update

• Note3: If while loop condition is never false


(always true) then the loop becomes infinite loop
(body executed infinitely)

17
2.While loop

Exercise: Write an algorithm that allows reading an integer x (x≥0), then


subtracting 11 from x until x becomes negative.

Display the number of subtraction operations performed.

18
2.While loop
Analysis Algorithm sub;
Var
1.Read the value of an integer x x, cnt: integer;
Begin
2.Initialize the subtraction counter cnt
Read (x);
to 0
cnt  0;
3.If x≥0 then substruct 11 from x and While (x>=0) do
increment the number of subtraction begin
cnt by 1. x x-11;
cnt cnt +1;
4.if x≥0 then go to (3) else exit loop end ;
5.Display value of cnt Write (″The number of subtraction done is :″, cnt);
End.

19
3.Do .. While loop

20
3. Do .. While

• It is similar to a While loop, except that a Do..While


Action
loop is executed at least once. So, this structure
actually allows repeating an action 1, 2, or multiple
False True
times. Condition

21
3. Do .. While

Syntax :
Action
Do
Action ;
While Condition ; False True
Condition

22
3. Do .. While

Action
• Note1: The body of the Do while loop may at
least be executed once. So, this structure
actually allows repeating an action 1, 2 or Loop update
multiple times.

• Note2: If condition is never False (always True) False


Condition
True
then the loop becomes infinite loop (body
executed endlessly).

23
3. Do .. While
Exercice: Do the trace (sequence) for Algorithm subt;
✓ x = 51. Var
• Example : Previous exercise x, cnt: integer ;
✓ x=-3
Design the Flow Diagram Begin
Read (x);
cnt  0;
Do
if x>=0 Then cnt cnt +1;
x x-11;

While x>= 0 ;
Write (‘The number of subtraction done is :’, cnt);
End.

24
3. Do .. While
Exercise
Write an algorithm that allows to read the value of an integer n , knowing
that n must be less than or equal 100.

Algorithm N_value;
Var
n: integer ;
Begin
Do
Read (n);
While n > 100 ;
Write (n);
End.
25
4. For and While loop

Example 1 Equivalent algorithm using While


Algorithm ascend; Trace Algorithm ascend2;
Var A, i : integer; Var A, i : integer; Trace
A i Begin
Begin A 2 ;
2 1
i  1;
A 2 ; 2 4 While i <=10 do
For i  1 To 10 Step 3 do 8 7 begin
A A*i; 56 10 A A*i;
i  i+3;
560
Write (A); end;
End. Write (A);
End.
Result : 560
26
4. For and While loop

Example 2 Equivalent algorithm using While

Algorithm descend; Trace Algorithm descend2;


Var A , i : integer; Var A , i : integer;
Begin
Begin A i
A 2 ;
A 2 ; 2 10
i  10;
For i  10 To 1 Step -2 do 12 8 While i >=1 do
A A+i; 20 6 begin
Write (A); 26 4 A A+i;
End. i  i-2;
30 2
end;
32 0 Write (A);
End.
Result : 32
27
4. For and While loop

Example 3 Iteration using While loop

Trace Algorithm iteration2;


Algorithm iteration; Var A, K, i : integer;
Var A, K, i : integer; Begin
A i K
Begin
5 1 5 A  5;
i  1;
A  5; 5 2 10 While i <=5 do
For i 1 to 5 do 10 3 30 begin
begin K A*i;
30 4 120
K A*i; A K ;
A K ; 120 5 600 i  i+1;
end; 600 6
end;
Write(A); Write(A);
End. End.

28
4. Nested loop
All types of loops can be nested inside each other

Example 4 Trace
i j Result For i  1 to 3 do
For i  1 to 3 do 1 1 1 begin
2 2 j1;
For j  1 to 2 do
3 while j <= 2 do
Write (i*j); 2 1 2 begin
2 4
Write (i*j);
3
j j+1;
3 1 3
end;
2 6
3
End;
4 29
Translation into Language

30
Translate For loop in C

identical

31
Translate For loop in C

32
Translate While loop in C

33
Translate Do..while in C

34
Exercises with solutions

35
Exercises

1. Write an algorithm that displays the numbers from 1 to 100,


using ‘For’ loop.
2. Write an algorithm that finds the sum of all the even numbers
from 1 to 100, using a while loop.
3. Write an algorithm that allows to read the value of the integer
n , knowing that n must be greater than 100.
36
Solutions
Exercise 1
Write an algorithm that displays the numbers from 1 to 100, using “For” loop.

Algorithm display_numbers;
Var i : integer ;
Begin
For i  1 To 100 do
Write (i);
End .

37
Solutions
Exercise 2
Write an algorithm that finds the sum of all the even numbers from 1 to 100, using a while
loop.
Algorithm sum;
Var number , sum: integer ;
Begin
number  1;
sum  0;
While number <= 100 do
begin
if (number mod 2) =0 then sum  sum + number;
number  number + 1;
end;
Write (“The sum of even numbers from 1 to 100 is “, sum);
End .
38
Solutions
Exercise 3
Write an algorithm that allows to read the value of the integer n , knowing that n must
be greater than 100.

Algorithm numbers;
Var n: integer ;
Begin

Do
read(n);
While (n<=100);
End .

39
Additional exercises
4. Write an algorithm that checks if a natural number a is prime or not.
(A prime number is divisible only by 1 and itself).
5. Write an algorithm that calculates the GCD (Greater Common Divisor) of
two given numbers. E.g. GCD of 18 and 12 is 6
• Tip : repeat subtracting the smaller number from the larger number
until they equal.

6. Write an algorithm that determines whether a given natural number is a


“Perfect” number or not. A perfect number is equal to the sum of its
proper divisors except itself. E.g. 6 is perfect because 6=1+2+3.
40

You might also like