0% found this document useful (0 votes)
5 views16 pages

Understanding Control Structures in Programming

This document describes control structures in programming, particularly conditional structures and loops. It explains in detail the conditional structures If...Then...Else and If...Then, as well as Boolean expressions and Boolean variables.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Understanding Control Structures in Programming

This document describes control structures in programming, particularly conditional structures and loops. It explains in detail the conditional structures If...Then...Else and If...Then, as well as Boolean expressions and Boolean variables.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

K.

Zabo Control structures Professional University Center

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.

There are two main types of control structures:


- conditional structures will allow certain instructions to be executed only if
under certain conditions
- repetitive structures, also called loops, will allow to repeat some
instructions a certain number of times, under certain conditions

I. Conditional structures

[Link]

Conditional structures allow executing different instructions depending on


of certain conditions. A condition (also called a conditional or logical expression)
is evaluated, meaning it is judged to be true or false. If it is true, a process (a
or several instructions) is executed; if the condition is false, another instruction will be
executed, and then the program will continue normally.

There are 2 main types of conditional structures


1

L3-M1-M2-COMPUTER-SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center

alternative structures (If...Then...Else)


conditional structures in the strict sense (If...Then)

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.

Suppose we need to write a message in a program indicating whether the


the value of a variable, named a, is positive or negative.

For this, we will use the alternative structure.

Display 'enter a number'


Saisirn
Sin > 0
So //in the case where the expression n>0 is true Display
positive value
Otherwise if the expression n>0 is false Display
negative or zero value
Finish

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.

The general syntax of this structure is as follows:

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.

Example of alternative structure with 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

Display 'Enter two numbers'


Enter nb1, nb2
Display 'enter the first letter of the desired operation'
Saisirop

s
So then res nb1 + nb2
display "the sum is", res block number 1
Sinonresn b1 nb2 *
display "the product is", res
Finish block n°2
Fin

[Link]

A conditional expression (or logical expression, or Boolean expression) is a


expression whose value is either TRUE or FALSE. There are several types of expressions
conditional.

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)

The comparison symbols usable in algorithms are:

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.

We would write for this purpose:

Six is greater than y.

So display x - y
Otherwise display y - x
Finished

2. Complex conditions

Conditions (or conditional expressions) can also be complex, that is to say


composed of several simple conditions or boolean variables connected to each other by the
opérateurs logiqueset,ou,non.

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

Boolean variables, like conditional expressions, are either true or false.


false. We can therefore assign a conditional expression to a boolean and we can also
find a boolean variable instead of a conditional expression.
Boolean variables and conditional expressions are equivalent. Every time
that we can find a conditional expression, we can also find a variable
boolean.

Ex:

Program intervals Var


belongs: boolean
nb: real
Start
Display 'please enter a real number' Input
nb
belongs = (nb < 10 AND nb > 5) OR (nb > 15 AND nb < 20)
If it belongs
So "The number belongs to the defined intervals"
Otherwise, "The number does not belong to the defined intervals"
Finnish
End

This program takes a number and displays whether that number is within the intervals 510.
or 15-20

II. The structureYes. So (conditional)


This structure is used if one wants to execute a statement only if a condition is
true and do nothing if the condition is false. It avoids writing Otherwise nothing.

The syntax of a conditional structure is as follows:

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 piece of algorithm concerned is:


Simont > 1000Alormont
= mont * 0.9
Finish
Display

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.

III. Repetitive structures or loops


Repetitive structures, also called loops, allow for repetition of a
treatment (that is to say a simple or composite instruction) as many times as it
is necessary: either a determined number of times, or as long as a condition is
true.
There are three main types of repetitive structures:
- The structure As long as...Doing, which allows you to execute an instruction as long as a
condition is met
- the structureThat allows to repeat an instruction a certain number of times - the
Repeat…Until, which as its name suggests, allows to repeat a
instruction until a condition is met.

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.

A. Loop While ...Do

The While … Do loop allows you to repeat a process as long as an expression


The condition is true. If initially the condition is not true, the process will not be
not executed. We can see that the While loop has something in common with the structure
conditional where if the condition is not true, the process is not executed.

Syntax:
As long as <execution condition> Do

<processing> simple instruction or block of instructions

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.

Operation of this program

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

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

Instruction executed variable or value afterwards display


evaluated expression the instruction on the screen
Show "This program … This program calculates the cube...
Display "Enter a number" Enter a number
saisirx x 10 10
So what≠ 0 x≠ 0 TRUE
display x * x * x x*x*x 100 100
Enter a number... Enter a number or 0 for...
enter x -3 -3
Tantquex≠ 0 x≠ 0 TRUE

display x*x*x x*x*x -9 -9


Display "Enter a number…" x -3 Enter a number or 0 for...
saisirx x 0 0
So what≠ 0 x≠ 0 FALSE
Display 'End' End

[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

For <counter> from <initial value> to <final value> [step <increment>] Do

<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

The For loop is actually a simplification of the While loop.

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

IV. Iterative Ladder Framework


An iteration is a loop where the value of a variable depends on its value in the current turn.
previous. The variable in question is found both on the left and right side of an assignment.
The iterative approach (the use of iterations) is used to solve many
programming problems. To become familiar with this complex process, we will
study simple and fundamental algorithmic problems.

To buy and accumulate


How to count the number of loop iterations
in a While loop? (systematic counting)

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 instructioncounter + 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

2. How to count only the negative cubes?


(selective counting)

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

3. How to count multiple things at once?


multiple counting

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
cptnegcptneg + 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

L3-M1-M2 COMPUTER SCIENCE-TELECOMMUNICATIONS


K. Zabo Control structures Professional University Center

We cannot do all the necessary multiplications at once because we do not know.


how much the exponent is worth at the time of writing the program. The programmer does not know what
The exhibitor will type the user. There are infinite possibilities.
To overcome this difficulty, we will repeat the multiplication by x n times in a loop.
We use the for loop because we know how many times we are repeating the multiplication: n times.
What do we do with the result of the multiplication by x: we assign it to a variable result, which
We will use in the next round. What do we multiply by x each round: the result of
previous tour.
And in the first round? There are no results yet. Just initialize the result variable.
with 1.

Hence the following solution: Program


exponent
Var
integer x is the number and n is the exponent
Start
Please enter a number and then its exponent
Saisirx, n
res1 //initialization of the result
From Pouride1 to Faire
res res * x iteration
FinPour
power
End

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.

loop tour value of res


(meter value)
before 1 thanks to the initialization
1er(i1 ) 5 1 * x (x is 5)
2th(i2) 25 x * x x²
3th(i3) 125 *x
525 x3* x be x4
4th(i4)
it is worth n therefore stop the loop
after 525 the desired result

5. Find the minimum of a sequence of numbers

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.

Minimum programming variable

nb: real //for entering minimum numbers


real //minimum

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
minn 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

6. The iterative approach: general case

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

state final state


intermediate state no. 1
intermediate n°2

1ertour 2nd round 3rd round

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

2) See which instructions allow progress to the intermediate state


Next (for example, for the minimum, how to find the new minimum
when a new number is typed). Be sure to pay attention to the order of the instructions.

3) It will be asked what condition(s) the state we have reached is final.


(in the case of the minimum, it is when all the numbers have been entered, that is to say
when the counter is more than 100

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

CHAPTER 2 CONTROL STRUCTURES


Statement of Exercises
Exercise 2.1
Write an algorithm that asks the user for a number, and then informs them whether this number is positive or negative.
negative (we set aside the case where the number is zero).

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:

• Chick from 6 to 7 years old


• Pupil
• Minime from 10 to 11 years old
"Cadet" after 12 years Can we conceive several equivalent algorithms leading to this result?

15

L3-M1-M2-COMPUTER SCIENCE-TELECOMS
K. Zabo Control structures University Professional Center

16

L3-M1-M2-COMPUTER-SCIENCE-TELECOMMUNICATIONS

You might also like