Understanding Control Structures in Programming
Understanding Control Structures in Programming
Chapter 2:
Control structures:
fundamentalnotions
Introduction
Conditional structures
The loops
The iterative approach
Introduction
In procedural programming as in algorithms (which respect the constraints
Fundamentals of programming!), the order of instructions is crucial.
The processor executes the instructions in the order they appear in the
program. It is said that execution is sequential.
Once the program has finished one instruction, it moves on to the next one. As long as a
the instruction is not finished, it waits before continuing. For example, an instruction of
Input will wait for the user to enter a value from the keyboard before continuing.
Sometimes, it is necessary for the processor not to execute all the instructions, or else
that he repeats the same instructions several times. To do this, it will be necessary to break the
sequence. This is the role of control structures.
I. Conditional structures
[Link]
L3-M1-M2-COMPUTER-SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center
In the course of an algorithm, one often has to choose between two actions, depending on a
condition concerning the value of certain data. The alternative structure will allow
to make choices.
If the condition n < 0 mentioned after the word is true, we execute what follows after the
So, if the condition is false, we execute what is written after the word Otherwise.
If<condition>
So
Otherwise
Finnish
For better readability of the program, we offset the Then and the Else relative to the If.
We will make a vertical line appear.
For now it may seem superfluous, but in fact when programs become more complicated,
These writing rules greatly facilitate their proofreading.
Let us recall that the treatments appearing after the words Then and Otherwise can be
made up of a simple instruction, as in our first example, but also of a
set of instructions, called instruction block.
We want a program that remembers and displays the sum or the product of 2 numbers.
depending on the user's choice. This program must enter the two desired numbers as well as
the letter representing the operation to be performed. If the letter is s (like sum), it calculates and
display the sum, and if the letter is p (or any other character), the program should calculate and
display the product.
L3-M1-M2-COMPUTER-SCIENCE-TELECOMS
K. Zabo Control structures Professional University Center
Choice program
nb1
character
Start
s
So then res nb1 + nb2
display "the sum is", res block number 1
Sinonresn b1 nb2 *
display "the product is", res
Finish block n°2
Fin
[Link]
1. Simple comparisons
In our two examples, the conditions we encountered (a < 0) and (op ="s") are some
simple conditions. A simple condition is a comparison of two expressions of the same
type. (a<0 integer or real type, op = "s" character type)
For character comparisons, the ASCII order is used, which respects the order
Alphabetical. A letter placed before another in alphabetical order will be less than
the other.
"a" is less than "b", but "s" is greater than "m".
Attention, a simple condition does not mean a short condition. A simple condition
maybe the comparison of two expressions like:
(a + b - 3) * c ≤ (5 * y - 2) / 3
Application
L3-M1-M2-COMPUTER_SCIENCE-TELECOMS
K. Zabo Control structures Professional University Center
Suppose we want to display the absolute value of the difference between two numbers.
Integers. These integers will be denoted x and y.
We want to display x - y if x is greater than y and y - x otherwise.
So display x - y
Otherwise display y - x
Finished
2. Complex conditions
Examples:
Sia < 0etb < 0
So...
If (a + 3 = b and c < 0) or (a = c * 2 and b≠ c) So
…
And
A compound condition made up of two simple conditions connected by 'and' is true if both are true.
conditions are true.
The condition is a < 0 and
b<0
is true if a < 0 is true and if b < 0 is true
Or
A compound condition made up of two simple conditions separated by or is true if at least one of them is true.
simple conditions are true.
a < 0oub < 0
is true if a < 0 or if b < 0 or if a and b are negative.
No
A condition preceded by not is true if the simple condition is false and vice versa.
not(a < 0) is true if a >= 0
The use of parentheses helps to resolve any potential operator precedence issues.
logics.
L3-M1-M2-IT-TELECOMS
K. Zabo Control structures Professionalized University Center
3. Boolean variables
Ex:
This program takes a number and displays whether that number is within the intervals 510.
or 15-20
If<condition>Then
<treatment>
Finish
Example:
In a billing calculation program, we want to apply a 1% discount if the amount
the invoice exceeds 1000F.
Let's assume that the variable containing the invoice amount is called mont. We want to write
the algorithm that displays the amount to be paid.
If the amount is less than 1000F, we just want to display the amount as is. But if the
If the amount is greater than 1000F, you need to take the discount into account and calculate the new amount.
amount.
5
L3-M1-M2-COMPUTER SCIENCE-TELECOMMUNICATIONS
K. Zabo Control structures Professional University Center
The program applies the reduction only if the amount is greater than 1000F. Otherwise, it
does not perform any special processing and moves to the next instruction. In all cases, the
amount is displayed.
Only the While loop is fundamental. With this loop, you can achieve everything.
the other loops while the reverse is not true. The For loop is also widely used because
it simplifies the While loop when the number of loop iterations is known
in advance. The Repeat loop, which is very rarely used, will be studied in the next chapter.
Syntax:
As long as <execution condition> Do
FinTantque
L3-M1-M2-IT-TELECOMS
K. Zabo Control structures University Professional Center
Let's assume we want the algorithm to calculate the cube of the numbers provided to it and
that to stop, the user must enter 0.
If the entered number is 0, we do not want to display the cube and the process is finished. If the
the entered number is different from 0, we display its cube and we start again (we ask to enter
a name, we enter it, etc)
We therefore want to execute the instructions in the following order:
enter a number
check the execution condition (x≠ 0)
if x equals 0, we exit the loop
otherwise we display the cube and wait for the user to enter another number
We check the execution condition (x≠ 0
if x is 0, we exit the loop
Otherwise, we display the cube and wait for the user to enter another number.
…
It can be seen that after entering the first number, we repeat the last three instructions.
We will therefore be able to include them in a loop. The continuation condition (x≠ is
registered after the whenever. This condition is checked every time we have completed the
loop treatments.
Programmecube
Var
x :Integer
Start
This program calculates the cube of the numbers you enter. To stop, type 0.
Display 'Enter a number'
Saisirx
So what≠ 0Do
Display "the cube of ", x, " is ", x*x*x
Display 'Enter a number or 0 to stop'
Saisirx
FinTQ
Display 'End'
End
The number of treatment repetitions is not explicitly stated; it will depend on the
data provided to the program, namely the entered numbers.
It first displays the input label and waits for the user to enter a number, which is
so entered in variable x.
Then, the condition following the While is evaluated. If the user enters as the first
name 0, the condition is false and the body of the loop will not be executed and the processor
will continue to the first instruction following the FinTQ (Display 'Fin'). If the user enters
a number different from 0, its cube is calculated and displayed and a new number is entered. At
At the FinTQ level, the processor makes a branch, meaning that it does not execute
L3-M1-M2-COMPUTER SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center
the following instruction but goes back to the beginning of the loop and reevaluates the expression
conditional.
The user can calculate as many cubes as they want and when they want to stop, they just need to
taper 0. It is said that 0 is a flag value, meaning it indicates the end of a
treatment.
The trace of an algorithm represents the value of the different pieces of information in a program.
during its execution. It is strongly recommended to trace an algorithm in order to
check that it works.
The first thing to do is to choose data on which we will perform the test of
the algorithm. For this data, we manually calculate the expected result. Then we perform the
trace and compare the expected result with the trace result which should be the same
(otherwise, there is an error somewhere...)
Let's trace the previous algorithm with the following data given
x expected result
10 display of 100
-3 display of -9
0 Display of End and stop of the program
[Link]
The For loop allows repeating a statement a known number of times. It has the
formalism following:
L3-M1-M2-COMPUTER SCIENCE-TELECOMMUNICATIONS
K. Zabo Control structures University Professional Center
<treatment>
FinPour
It allows you to do the same thing as the While loop but faster.
less when the number of repetitions is known.
The counter variable is of integer type. It is initialized to the initial value. The counter
implicitly increases by the increment at each repetition of the process.
When the counter variable reaches the final value, the process is executed one last time.
then the program exits the loop.
By default, the increment is 1
Example:
Pourxde1jqà20Make
increment
automatic<processing>
FinPour
Thanks to such a structure, the processing will be repeated 20 times. We could do the same.
choose with a while loop, but you need to initialize the counter variable and
increment it explicitly.
X 1
As long as x <= 20 Do
processing
x x+1
As Long As
Application
Let's display the multiplication table of 7. For this, we will use a variable a that varies from
1 to 10 and multiply this variable by 7 at each increment. This variable will also
serve as a counter for the For structure.
Multiplication program 7
Vara
Whole
Beginning
Pourade 1 to 10 no 1
Will display, " * 7 = ", a * 7
EndFor
End
L3-M1-M2-COMPUTER-SCIENCE-TELECOMMUNICATIONS
K. Zabo Control structures Professional University Center
Let's take up the cube program again. Assume now that we need to count
How many cubes have been calculated? How to proceed?
Just use a variable that will serve as a counter. Before entering the loop, the
the counter is set to 0. This counter is incremented by 1 at each loop iteration. To do this, we
add the counter instructioncounter + 1 inside the loop: Such a
instruction is called incrementation.
Programmecube
Var
x: Integer
counter
Start
… (cf III)
So what≠ 0Do
Display "the cube of ", x, " is ", x*x*x
counter counter + 1
Enter a number or 0 to stop
Saisirx
FinTantque
Display "You requested", counter, "cubes" End
If we only want to increase the counter under a certain condition (here, in the case where the
the entered number is negative), just move the increment inside a
conditional structure.
Programmecube
Var
Integer
counter: integer
Start
… (cf III)
10
L3-M1-M2-COMPUTER-SCIENCE-TELECOMS
K. Zabo Control structures Professional University Center
So what≠ 0Do
Display "the cube of ", x, " is ", x*x*x
If x<0 Then counter counter + 1
FinSi
Display 'Enter a number or 0 to stop'
Enterx
FinTantque
Display "You have obtained", counter, "negative cubes"
End
One might want to count several things simultaneously in the same loop. For
taking up our example, we might want to count the negative cubes but also the
cube pairs. In this case, a single counter is no longer sufficient. It is necessary to use as many counters.
that we have things to count.
Programmecube
Var
x :integer
integer negative cube counter
integer // counter of even cubes
Start
… (see III)
So much for that≠ 0Do
Display "the cube of ", x, " is ", x*x*x
If x < 0 Then
cptnegcptneg + 1
FinSi
If x*x*x mod 2 = 0 Then
cptpair cptpair + 1
FinSi
Display "Enter a number or 0 to stop"
Saisirx
FinTantque
Display "You have obtained", cptnegr, "negative cubes, and", cptpair, "even cubes" End
4. Calculate the result of xnwith an iteration
In some languages, the exponent operator does not exist. Let's assume that we cannot
not to be used in algorithmics. We will write the algorithm that allows to calculate a
number to a given exponent. The number x and the exponent n are entered.
Reminder:
x1=x
x2= x*x x1*x
x3= x*x*x x2*x
x = x*x*x*x
4 x 3*x
…
11
The result variable truly represents the desired outcome only at the end of the loop.
Meanwhile, it takes intermediate values that serve to progress from an initial value.
known towards the sought final value.
Let's execute the traced part of the gray algorithm in the case where the user inputs 5 for x.
and 4 for n.
We want to find the smallest among a list of 100 numbers entered by the user.
How to do it?
12
L3-M1-M2-COMPUTER SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center
It is unrealistic to declare 100 variables and compare them all one by one.
The input of the numbers from the list will be done inside a loop using only one
variable.
To obtain the minimum, we will use an iteration.
At each loop iteration, an additional number is entered. If the minimum is known
among all the previous numbers entered, it is sufficient to compare the new number to this
minimum to have the new minimum (among all the numbers, including the last). If
the new entered number is smaller than the smallest of the previous numbers, so the
the new number is the new minimum among all the entered numbers. Otherwise, the minimum
stay the same.
Before the first input, there is no minimum. In fact, when a single number is entered,
he is definitely the minimum. So we start the loop from the second one
entered element.
Beginning
Enter a number
Enter min The first number entered is the minimum of the numbers already entered.
(he is the only one!!)
Pour from 2 to 100. For all other elements from the 2nd to the last
Please enter another number
Saisirnb we store it in memory
Sinb < min Then if it is smaller than the minimum found in the previous round
minn b he is the new minimum among the already entered numbers
Finished
Finpour At the end of the loop, min is the minimum of the 100 numbers entered.
The minimum of the entered numbers is, min
End
13
L3-M1-M2-COMPUTER-SCIENCE-TELECOMMUNICATIONS
K. Zabo Control structures University Professional Center
An iteration consists of a progression from an initial state to a final state, the one that is
searched. A state is represented by the values of the variables at a given moment. The
progression towards the desired state occurs by passing through states
intermediaries.
A loop allows progress from one state to another, getting closer to the final state.
When the final state is reached, the loop must stop.
state
initial
To 'discover' an iteration, there is no magic recipe. You have to use your imagination.
and his intelligence.
Nevertheless, the following approach can help to find an iteration to solve a
problem.
1) Seek an intermediary state between the initial state and the final state (for example, for
the minimum studied in the previous paragraph, the intermediate state is that we have found
the minimum of the i numbers already typed). One does not care about how one
has reached this state, it is assumed that this state has been achieved
4) Finally, find out how to start. One must find an initial state where all the
values are known and allow for a transition to an intermediate state. Some
variables must be initialized. (in the case of the minimum, the minimum is known
when only one number has been entered
14
L3-M1-M2-COMPUTER SCIENCE-TELECOMS
K. Zabo Control structures University Professionalization Center
Exercise 2.2
Write an algorithm that asks the user for two numbers and then informs them whether their product is negative or not.
positive (we leave aside the case where the product is zero). However, be careful: we must not calculate the product of
two numbers.
Exercise 2.3
Write an algorithm that asks the user for three names and then informs them whether they are sorted or not.
the alphabetical order.
Exercise 2.4
Write an algorithm that asks a number from the user, and then informs them whether this number is positive or negative.
negative (this time we include the treatment of the case where the number is zero).
Exercise 2.5
Write an algorithm that asks the user for two numbers and then informs them whether the product is negative or not.
positive (this time we include the handling of the case where the product can be null). However, be careful, we must not
calculate the product!
Exercise 2.6
Write an algorithm that asks the user's age for a child. Then, it informs them of their category:
15
L3-M1-M2-COMPUTER SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center
16
L3-M1-M2-COMPUTER-SCIENCE-TELECOMMUNICATIONS