0% found this document useful (0 votes)
4 views59 pages

Algorithm Exercises and Solutions Guide

The document contains numerous algorithmic exercises and their solutions. The exercises cover various topics such as variable manipulation, arithmetic and logical operations, loops, and functions. The document is divided into several sections.

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)
4 views59 pages

Algorithm Exercises and Solutions Guide

The document contains numerous algorithmic exercises and their solutions. The exercises cover various topics such as variable manipulation, arithmetic and logical operations, loops, and functions. The document is divided into several sections.

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

[Link].

tech 1

ALGORITHMICExerciceS

Summary
Statement of Exercises
Corrections of the Exercises ............................................................................................................ 3
PART 2 Statement of Exercises........................................................................................................ 6
Solutions to the Exercises ............................................................................................................ 6
PART 3 Statement of Exercises............................................................................................... 7
Solutions to the Exercises ............................................................................................................ 8
PART 4 Statement of Exercises..................................................................................... 10
Corrections of the Exercises .......................................................................................................... 12
PART 5 Statement of Exercises
Answers to the Exercises .................................................................................. 20
PART 6 Statement of Exercises
Corrections of the Exercises .......................................................................................................... 27
PART 7 Statement of Exercises
Solutions to the Exercises .......................................................................................................... 32
PART 8 Statement of Exercises............................................................................................. 35
Corrections of Exercises .......................................................................................................... 37
PART 9 Statement of Exercises............................................................................................. 41
Answers to the Exercises .......................................................................................................... 44
PART 10 Statement of Exercises........................................................................................... 48
Exercise Solutions
PART 11 Statement of Exercises
Solutions to Exercises .......................................................................................................... 56

[Link]

[Link]
2

PART 1 Statements Exercises


Exercise 1.1

What will be the values of variables A and B after executing the following instructions?
Variables A, Ben Integer
Start
A←1
B←A+3
A←3
End

Exercise 1.2

What will be the values of the variables A, B, and C after executing the following instructions?
Integer variables A, B, C
Start
A←5
B←3
C becomes A plus B

A←2
C=B-A
End

Exercise 1.3

What will be the values of the variables A and B after executing the following instructions?
VariablesA, Ben Integer
Beginning

A←5
B←A + 4
A←A+1
B←A-4
End

Exercise 1.4

What will be the values of the variables A, B and C after executing the following instructions?
Variables A, B, Integer Cen
Beginning

A←3
B←10
C=A+B
B←A+B
A←C
End

Exercise 1.5

What will be the values of variables A and B after executing the following instructions?

[Link]
3

Variables A, Ben Integer


Beginning

A←5
B←2
A←B
B←A
End

Morality: do the last two instructions allow to exchange the two values of B and A? If so
If we reverse the last two instructions, does it change anything?

Exercise 1.6

More difficult, but it's an absolute classic that must be mastered: writing an algorithm
allowing the exchange of values between two variables A and B, regardless of their content
preliminary.

Exercise 1.7

A variant of the previous one: we have three variables A, B, and C. Write an algorithm
transferring to B the value of A, to C the value of B, and to A the value of C (always regardless of the
preliminary contents of these variables.

Exercise 1.8
What does the following algorithm produce?

Variables A, B, C Character
Start
A←"423"
B←"12"
C←A+B
End

Exercise 1.9
What does the following algorithm produce?

Variables A, B, Central Characters


Start
423
12
C←A&B
End

Exercise Solutions

[Link]
4

Exercise 1.1
After The value of the variables is:
A←1 A=1 B=?
B=A+3 A=1 B=4
A←3 A=3 B=4

Exercise 1.2
After The value of the variables is:
A←5 A=5 B=? ?
B←3 A=5 B=3 C=?
C=A+B A=5 B=3 C=8
A←2 A=2 B=3 C=8
C←B – A A=2 B=3 C=1

Exercise 1.3
After The value of the variables is:
A←5 A=5 B=?
B is equal to A plus 4 A=5 B=9
A←A+1 A=6 B=9
B←A-4 A=6 B=2

Exercise 1.4
After The value of the variables is:
A←3 A=3 B=? C=?
B←10 A=3 B = 10 C=?
C=A+B A=3 B = 10 C = 13
B←A + B A=3 B = 13 C = 13
A←C A = 13 B = 13 C = 13

Exercise 1.5
After The value of the variables is:
A←5 A=5 B=?
B←2 A=5 B=2
A←B A=2 B=2
B←A A=2 B=2
The last two instructions do not allow exchanging the two values of B and A.
since one of the two values (that of A) is here overwritten.
If we reverse the last two instructions, it will change nothing at all, except for the fact that
this time it is the value of B that will be overwritten.

Exercise 1.6
Start

C←A
A←B
B←C
End
We are forced to go through a so-called temporary variable (the variable C).

Exercise 1.7
Start

D←C
C←B

[Link]
5

B←A
A←D
End
In fact, no matter how many variables there are, a single temporary variable is enough...

Exercise 1.8
It can only produce a runtime error, since you cannot add characters.

Exercise 1.9
...On the other hand, we can concatenate them. At the end of the algorithm, C will therefore be equal to '42312'.

[Link]
6

PART 2
Enoncedes Exercises
Exercise 2.1

What result does the following program produce?


Variables val, double numeric
Start
Val←231
Double equals Val times 2

Write Val
Write Double
End

Exercise 2.2

Write a program that asks the user for a number, then calculates and displays the square of
this number.

Exercise 2.3

Write a program that reads the price excluding tax of an item, the number of items, and the VAT rate, and that
provide the total price including taxes accordingly. Ensure that labels are clearly displayed.
-

Exercise 2.4

Write an algorithm using string type variables, and displaying four


possible variants of the famous 'beautiful marquise, your beautiful eyes make me die of love.' We do not
don't worry about punctuation or capitalization.

Corrected Exercises
Exercise 2.1

[Link]
7

We will see 231 appear on the screen, then 462 (which is 231 * 2)

Exercise 2.2
Variables nb, car integer
Beginning

Enter a number:
Lirenb
square ← number * number

His square is:


End
In fact, we could just as easily save the variable 'carr' by replacing the two before-
last lines by:
His square is:
It's a matter of style; in one case, we prioritize the readability of the algorithm, in the other, we...
favor the economy of a variable.

Exercise 2.3
Variables nb, pht, ttva, pttcen Digital
Start
Enter the price excluding taxes:
Lirepht
Enter the number of items:
Lirenb
Enter the VAT rate:
Reading
pttc ← nb * pht * (1 + ttva)
The total price including taxes is:
Fin
Here too, we could squeeze a variable and a line by writing directly.
The total price including taxes is:
It's faster, lighter in memory, but a little harder to read (and to write!)

Exercise 2.4
Variables t1, t2, t3, t4 in Character
Start
beautiful Marquise
your beautiful eyes
I want to die
of love
Write t1 & " " & t2 & " " & t3 & " " & t4
Ecriret3 & " " & t2 & " " & t4 & " " & t1
Ecriret2 + " " + t3 + " " + t1 + " " + t4
Write t4 & " " & t1 & " " & t2 & " " & t3
End

PART 3
Exercise Enclosures
Exercise 3.1

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

[Link]
8

Exercise 3.2

Write an algorithm that asks the user for two numbers and then informs them if their product
is negative or positive (we set aside the case where the product is zero). However, be careful: we must not
Calculate the product of the two numbers.

Exercise 3.3

Write an algorithm that asks the user for three names and then informs them whether they are sorted or not.
not in alphabetical order.

Exercise 3.4

Write an algorithm that asks the user for a number, and then informs them whether this number is
positive or negative (this time we include the handling of the case where the number is zero).

Exercise 3.5

Write an algorithm that asks the user for two numbers and then informs them whether the product is
negative or positive (this time we include the treatment of the case where the product can be zero). Attention
However, one must not calculate the product!

Exercise 3.6

Write an algorithm that asks the user for a child's age. Then, it informs them of their
category :

• Chick from 6 to 7 years old


• Pupil aged 8 to 9 years
• Minime from 10 to 11 years
• "Cadet" after 12 years

Can we conceive several equivalent algorithms leading to this result?

Corrected Exercises
Exercise 3.1
Integer variables
Start
Enter a number:
Liren
If sin > 0 then
This number is positive

[Link]
9

Otherwise

This number is negative.


Finish
End

Exercise 3.2
Variables, an Integer
Start
Enter two numbers:
Lirem, n
If (m > 0 AND n > 0) OR (m < 0 AND n < 0) Then
Their product is positive
Otherwise

Their product is negative


Finish
End

Exercise 3.3
Variables a, b, Character
Start
Write "Enter three names in succession:"
Read, b, c
If b is less than c
These names are listed in alphabetical order.
Otherwise

These names are not classified


Finished
End

Exercise 3.4
Integer Variables
Begin
Enter a number:
Liren
If sin < 0
This number is negative
If Sin = 0 Then
This number is zero
Otherwise

This number is positive


Finish
End

Exercise 3.5
Variables, an integer
Beginning

Enter two numbers:


Lirem, n
If sim = 0 or n = 0 then
The product is worthless
If (m < 0 AND n < 0) OR (m > 0 AND n > 0) Then
The product is positive
Otherwise

The product is negative

[Link]
10

Finished
End
If we want to simplify the heavy writing of the ElseIf condition, we can always go through some
intermediate boolean variables. A Sioux trick also involves using an Xor
(this is one of the rare cases in which it is relevant)

Exercise 3.6
Variable integer
Beginning

Enter the child's age:


Readiness
Ifage >= 12 Then
Cadet Category
If Siage >= 10 Then
Write "Minimum Category"
If Siage >= 8 Then
Write 'Pupil Category'
If Siage >= 6 Then
Category Chick
Finsi
End
One can obviously write this algorithm in different ways, if only by starting
by the youngest category.

PART 4
Enoncedes Exercises
Exercise 4.1

Formulate an algorithm equivalent to the following algorithm:

[Link]
11

If Tutu > Toto + 4 or Tata = 'OK' then


Tutu←Tutu + 1
Otherwise

Tutu←Tutu – 1
Finnish

Exercise 4.2

This algorithm is intended to predict the future, and it must be infallible!


He will read on the keyboard the hour and the minutes, and he will display the time it will be one minute later.
for example, if the user types 21 then 32, the algorithm should respond:
In a minute, it will be 9:33 PM.
Note: It is assumed that the user enters a valid time. Therefore, there is no need to verify it.

Exercise 4.3

Just like the previous one, this algorithm must request a time and display another one. But
This time, he must also manage the seconds and display the time it will be one second later.
For example, if the user types 21, then 32, then 8, the algorithm should respond: "In one second,
It will be 21 hours, 32 minutes, and 9 seconds.
Note: here again, we assume that the user enters a valid date.

Exercise 4.4

A photocopy shop charges 0.10 euros for the first ten copies, 0.09 euros for the next twenty.
and 0.08 E beyond. Write an algorithm that asks the user for the number of photocopies.
made and displays the corresponding invoice.

Exercise 4.5

The inhabitants of Zorglub pay taxes according to the following rules:

• Men over the age of 20 pay taxes.


• women pay tax if they are between 18 and 35 years old
• the others do not pay taxes

The program will therefore ask for the Zorglubien's age and gender, and will then make a judgment on the
makes the resident taxable.

Exercise 4.6
The legislative elections in Northern Guignolerie follow the following rule:

• When one of the candidates receives more than 50% of the votes, they are elected in the first round.
• In the event of a second round, only candidates who have obtained at least
minus 12.5% of the votes in the first round.

[Link]
12

You must write an algorithm that allows the entry of scores for four candidates in the first
tour. This algorithm will then process candidate number 1 (and only him): it will say whether he is elected,
he wins, if he is in a favorable position (he participates in the second round by being in first place at
the outcome of the first round) or unfavorable (he participates in the second round without having been in the lead in the first.
tour).

Exercise 4.7
An automobile insurance company offers its clients four identifiable tariff categories.
by a color, from least to most expensive: blue, green, orange, and red rates. The rate depends on the
driver's situation:

• a driver under 25 years old and holding a license for less than two years finds themselves
assign the red rate, if he has never been responsible for an accident. Otherwise, the
the company refuses to insure him.
• a driver under 25 years old and holding a license for more than two years, or more
25 years old but holding a license for less than two years is entitled to the orange rate if he has not
never caused an accident, at the red rate for an accident, otherwise it is denied.
• a driver over 25 years old who has held a license for more than two years benefits from the
green rate if it is not the cause of any accident and the orange rate for an accident, of the rate
red for two accidents, and refused beyond
• Moreover, to encourage the loyalty of accepted customers, the company offers a contract.
the immediately most advantageous color if he has entered the house for more
a year.

Write the algorithm to enter the necessary data (without input validation) and to
address this problem. Before diving headfirst into this exercise, one might consider reflecting a bit
and realize that it is simpler than it seems (this is called doing an analysis!)

Exercise 4.8
Write an algorithm that, after asking for a day number, month, and year to
the user, returns whether it is a valid date or not.
This exercise is certainly lacking in originality, but after all, in algorithms
like elsewhere, one must know their classics! And when one has done that once in their life, one
fully appreciate the existence of a "date" numeric type in some languages...)
It is probably not useless to quickly remind that the month of February has 28 days, unless if
the year is a leap year, in which case it has 29. The year is a leap year if it is divisible by
four. However, years divisible by 100 are not leap years, but years divisible
By 400 they are. Phew!
One last little detail: you do not yet know how to express correctly in pseudo-code.
the idea that a number A is divisible by a number B. Also, you will limit yourself to writing in good
telegraphists say "A dp B" when A is divisible by B.

Corrected Exercises
Exercise 4.1
No difficulty, just apply the rule of transforming OR into AND seen in class (law of
Morgan). However, be careful with the rigor in transforming conditions into their opposite...

[Link]
13

If Tutu <= Toto + 4 AND Tata <> 'OK' Then


Tutu←Tutu - 1
Otherwise

Tutu←Tutu + 1
Finish

Exercise 4.2
Variables, but Numeric
Start
Enter the hours, then the minutes:
Lireh, m
m←m + 1
Sim = 60 Then
m←0
h←h + 1
FinSi
Sih = 24Then
h←0
FinSi
In one minute it will be h hour(s) m minute(s)
End

Exercise 4.3
Variables, m, digital sign
Start
Enter the hours, then the minutes, then the seconds:
Read, m, s
s←s+1
Sis = 60Then
s←0
m←m + 1
Finally
Sim = 60
m←0
h←h + 1
FinSi
Sih = 24 So
h←0
Finish
In a second it will be
End
Exercise 4.4
Variables, digital pen
Beginning

Number of photocopies:
Liren
If sin <= 10 Then
p = n * 0.1
If Sin <= 30 Then
p = 10 * 0.1 + (n - 10) * 0.09
Otherwise

p = 10 * 0.1 + 20 * 0.09 + (n - 30) * 0.08


FinSi
The total price is:
End

[Link]
14

Exercise 4.5
Variable sex character
Digital Variable Age
Variables C1, C2 in Boolean
Start
Enter gender (M/F):
Liresex
Enter the age:
Reading
sex = 'M' AND age > 20
C2←sex = "F" AND (age > 18 AND age < 35)
SiC1 or C2Then
Taxable
Otherwise

Non Taxable
FinSi
End

Exercise 4.6
This exercise, from a purely algorithmic point of view, is not very difficult. However, it represents
dignity the category of tricky statements.
Indeed, nothing is easier than to write: if the candidate has more than 50%, he is elected, otherwise if he has more than
12.5%, he is in the second round, otherwise he is eliminated. Hehehe... but we must not forget that the
a candidate can very well have scored 20% but still be eliminated, simply because
one of the others got more than 50% and therefore there is no second round!...
Moral: never rush into programming before carefully conducting the analysis of
problem to address.
Variables A, B, C, Den Numeric
Start
Enter the scores of the four candidates:
Read A, B, C, D
C1 is greater than 50

C2←B > 50 or C > 50 or D > 50


C3 is greater than or equal to A and A is greater than or equal to B and A is greater than or equal to C and A is greater than or equal to D

C4←A >= 12.5


SoC1Then
Elected in the first round
Either C2 or Not (C4)
Beaten, eliminated, out!!!
Otherwise, if C3 then
Favorable ballot
Otherwise

Unfavorable ballot
FinSi
End

Exercise 4.7
Here again, we illustrate the usefulness of a good analysis. I propose two different corrections. The first
follows the statement step by step. It's correct, but it's really cumbersome. The second version relies on a
True understanding of a situation not as complicated as it seems.
In both cases, the use of boolean variables significantly clarifies the writing.
So, first correction, we follow the text of the statement step by step:

[Link]
15

Variables age, perm, acc, assurance Numeric


Variables C1, C2, C3 in Boolean
Character of Variables
Start
Enter the age:
Read
Enter the number of years of license:
Readperm
Enter the number of accidents:
Lireacc
Enter the number of years of insurance:
Lireassur
age >= 25
C2←perm >= 2
C3←assur > 1
If Not(C1) and Not(C2) Then
If less than zero then

Red
Otherwise

Refused
FinSi
Either (Not(C1) and C2) or (C1 and Not(C2)) then
If Siacc = 0 Then
Orange
If Siacc = 1 Then
Red
Otherwise

Refused
FinSi
Otherwise

If Siacc = 0 Then
Green
If SinonSiacc = 1 Then
Orange
If Siacc = 2 Then
Red
Otherwise

Refused
FinSi
FinSi
SoC3
Sisitu = "Red"
Orange
Otherwise, it's 'Orange' then
Orange
Green
Blue
FinSi
FinSi
Your situation:
End
Do you find this complicated? Oh, certainly yes, it is! And all the more so since when reading between the lines,
one could see that this jumble of prices actually covers a very simple logic: a
point system. And just counting the points is enough to make everything clear... Let's just go back
after the assignment of the three boolean variables C1, C2, and C3. We write:

[Link]
16

P←0
IfNot(C1)Then
P←P + 1
FinSi
IfNot(C2)Then
P←P + 1
FinSi
P←P + acc
If P < 3 and C3 Then
P←P - 1
FinSi
SiP = -1 Then
Blue
IfSiP = 0Then
Green
IfSiP = 1Then
Orange
IfSiP = 2 Then
Red
Otherwise

Refused
FinSi
Your situation:
End
Cool, isn't it?

Exercise 4.8
As for the start of this algorithm, there is no difficulty. It is just mindless input and
not even mean:
Variables J, M, A, JMax numeric
Variables VJ, VM, Ben Boolean
Start
Enter the day number
ReadJ
Enter the month number
ReadM
Enter the year
ReadA
It is obviously then that the trouble begins… The first way to approach the matter
consists of telling oneself that fundamentally, the logical structure of this problem is very simple. If
we create two boolean variables VJ and VM, representing respectively the validity of the day and
From the entered month, the end of the algorithm will be of biblical simplicity (the year is valid by
definition, if we set aside the Byzantine debate regarding the existence of the year zero) :
SiVJ and VMalors
The date is valid
Otherwise

The date is not valid


FinSi
The whole difficulty lies in correctly assigning the variables VJ and VM, according to the values of
variables J, M and A. In absolute terms, VJ and VM could be the objects of an assignment.
monstrous, with atrociously composed conditions. But frankly, writing these conditions
in one go is a tedious task with little interest. To avoid reaching such a
At the end, we can categorize the difficulty by creating two additional variables:

[Link]
17

B boolean variable that indicates whether it is a leap year


JMax: numerical variable that will indicate the last valid day for the entered month.

With all that, we can go in and come out alive.


We start by initializing our boolean variables, then we process the years, then the months, then
the days.
We denote 'dp' the condition 'divisible by':
B ← A dp 400 or (not(A dp 100) and A dp 4)
Jmax←0
VM is greater than or equal to 1 and M is less than or equal to 12

SiVMThen
IfM = 2 and BThen
JMax←29
If SIM = 2 then
JMax←28
If SiM = 4 or M = 6 or M = 9 or M = 11 Then
JMax←30
Otherwise

JMax←31
FinSi
VJ←J >= 1 and J <= Jmax
FinSi
This solution has the advantage of not complicating the structure of the tests too much, and in particular of not
repeat the final writing on the screen. The intermediate boolean variables save us from
composed conditions too heavy, but they remain serious nonetheless.

A different approach would be to limit the compound conditions, even if it means paying for it.
much more demanding structure of nested tests. Again, we avoid playing extremists
and we allow ourselves some compound conditions when it simplifies our existence. We could
also to say that the previous solution "starts from the end" of the problem (is the date valid or not?),
while the one that follows 'starts from the beginning' (what are the data entered from the keyboard?) :
If M < 1 or M > 12 Then
Invalid Date
IfSiM = 2 Then
If A dp 400Then
If J < 1 or J > 29 Then
Invalid Date
Otherwise

Valid Date
FinSi
IfThenA dp 100Then
If J < 1 or J > 28 Then
Invalid Date
Otherwise

Valid Date
FinSi
Otherwise, if A then 4
If J < 1 or J > 28 Then
Invalid Date
Otherwise

Valid Date
FinSi
Otherwise

If J < 1 or J > 28 Then

[Link]
18

Invalid Date
Otherwise

Valid Date
FinSi
FinSi
If SiM = 4 or M = 6 or M = 9 or M = 11 Then
If J < 1 or J > 30 Then
Invalid Date
Otherwise

Write 'Valid Date'


FinSi
Otherwise

If J < 1 or J > 31 Then


Invalid Date
Otherwise

Write 'Valid Date'


FinSi
FinSi
In this case, the final alternative (Valid date or invalid) is repeated a lot.
number of times. It is neither a good nor a bad thing in itself. It is simply a matter of
of stylistic choice.
Personally, I must admit that I clearly prefer the first solution, which stands out a lot.
more clearly the logical structure of the problem (there is only one alternative, as much as this
alternative should only be written once.

Finally, it is worth mentioning a very simple and elegant solution, perhaps a little more difficult to
imagine the first time, but with hindsight appears very immediate. Fundamentally, this
consists of saying that there are four cases for a date to be valid: that of a day between 1 and
31 in a month with 31 days, that of a day between 1 and 30 in a month with 30 days, that of a
day between 1 and 29 in February of a leap year, and that of a day in February included
between 1 and 28. Thus:
B ← (A is less than 4 and not (A is less than 100)) or A is less than 400

K1←(m=1 or m=3 or m=5 or m=7 or m=8 or m=10 or m=12) and (J>=1 and J<=31)
K2←(m=4 or m=6 or m=9 or m=11) and (J>=1 and J<=30)
K3 ← m = 2 and B and J >= 1 and J <= 29

K4←m=2 and J>=1 and J<=28


If K1 or K2 or K3 or K4
Valid date
Otherwise

Invalid date
FinSi
End

PART 5
Exercises Enunciated
Exercise 5.1

Write an algorithm that asks the user for a number between 1 and 3 until the
appropriate response.

[Link]
19

Exercise 5.2

Write an algorithm that asks for a number between 10 and 20, until the answer
suitable. In case of a response greater than 20, a message will appear: "Smaller!", and
Conversely, "Bigger!" if the number is less than 10.

Exercise 5.3

Write an algorithm that asks for a starting number and then displays the ten numbers.
Following. For example, if the user enters the number 17, the program will display the numbers from 18.
at 27.

Exercise 5.4

Write an algorithm that asks for a starting number, and then writes the table of
multiplication of this number, presented as follows (case where the user enters the number 7):
Table of 7:
7x1=7
7 x 2 = 14
7 x 3 = 21

7 x 10 = 70

Exercise 5.5
Write an algorithm that asks for a starting number, and then calculates the sum of the integers up to
this number. For example, if one enters 5, the program should calculate:
1 + 2 + 3 + 4 + 5 = 15

NB: we want to display only the result, not the breakdown of the calculation.

Exercise 5.6
Write an algorithm that asks for a starting number and calculates its factorial.
NB: the factorial of 8, noted as 8!, is equal to

1x2x3x4x5x6x7x8

Exercise 5.7
Write an algorithm that successively asks the user for 20 numbers, and then tells him/her afterwards.
which was the largest among these 20 numbers:
Enter number 1: 12
Enter number 2: 14
etc.

[Link]
20

Enter the number 20: 6


The largest of these numbers is: 14

Then modify the algorithm so that the program also displays in what position it had been.
enter this number:
It was number 2

Exercise 5.8
Rewrite the previous algorithm, but this time we do not know in advance how much the user
wants to input numbers. The input of numbers stops when the user enters a zero.

Exercise 5.9
Read the list of prices (in whole euros and ending in zero) of a customer's purchases. Calculate the
the amount he owes, read the amount he pays, and simulate the change given by displaying the
10 Euros, 5 Euros, and 1 Euro as many times as there are denominations of each type to give back.

Exercise 5.10
Write an algorithm that allows you to know your chances of winning at tiercé, quarté, quinté and
other voluntary taxes.
The user is asked for the number of horses running, and the number of horses played.
two displayed messages will be:
In order: one chance in X of winning
In disorder: a chance of 1 in Y to win

X and Y are given to us by the following formula, if n is the number of horses starting and p the
number of horses played (remember that the symbol ! means 'factorial', as in exercise 5.6
above) :
X = n! / (n - p)!
Y = n ! / (p ! * (n – p) !)
Note: this algorithm can be written in a simple way, but relatively inefficiently. Its
performances can be singularly enhanced by a small trick. You will start
to write in the simplest way, then you will identify the problem, and write a second
version allowing it to be resolved.

Corrected Exercises
Exercise 5.1
Integer Variable
Debut
N←0
Enter a number between 1 and 3
As long as N < 1 or N > 3

[Link]
21

LireN
If N < 1 or N > 3 Then
Incorrect entry. Please try again.
FinSi
As long as
End

Exercise 5.2
Integer Variable
Debut
N←0
Enter a number between 10 and 20
While N < 10 or N > 20
ReadN
If N < 10 Then
Write 'Bigger!'
IfSin > 20 Then
Write "Smaller!"
FinSi
As long as
End

Exercise 5.3
Variables N, Integer
Debut
Enter a number:
ReadN
The following 10 numbers are:
From N + 1 to N + 10
I will write

Next
End

Exercise 5.4
Variables N, an Integer
Debut
Enter a number:
LireN
The multiplication table of this number is:
Pouri from 1 to 10

WriteN, " x ", i, " = ", n*i


Next
End

Exercise 5.5
Variables N, i, Some Integer
Debut
Enter a number:
LireN
Som←0
Pouri←1 to N
Some
Next
The sum is:
End

[Link]
22

Exercise 5.6
Variables N, i, Integer
Debut
Enter a number:
LireN
F←1
Pouri←2 to N
F←F*i
Next
The factorial is:
End

Exercise 5.7
Variables N, i, PGen Integer
Debut
PG←0
Pouri←1 to 20
Enter a number:
LireN
If = 1 or N > PG Then
PG←N
FinSi
Next
The largest number was:
End
On line 3, we can put anything in PG, as long as this variable is assigned.
that the first passage in line 7 does not cause an error.

For the improved version, this gives:


Variables N, i, PG, IPGen Integer
Debut
PG←0
Pour 1 to 20
Enter a number:
ReadN
If = 1 or N > PGThen
PG←N
IPG←i
FinSi
Next
The largest number was:
He was seized in position number
End

Exercise 5.8
Variables N, i, PG, IPGen Integer
Debut
N←1
i←0
PG←0
As long as N <> 0
Enter a number:
ReadN
i←i + 1

[Link]
23

If Sii = 1 or N > PGThen


PG←N
IPG←i
FinSi
As long as
The largest number was:
He was seized in position number
End

Exercise 5.9
VariablesFF, somdue, M, IPG, Reste, Nb10F, Nb5F in Integer
Debut
E←1
somdue←0
As long as E <> 0
Enter the amount:
ReadE
somdue←somdue + E
As Long As
You must: E euros
Amount paid:
ReadM
Stay←M - E
Nb10E←0
As long as Remaining >= 10

Nb10E ← Nb10E + 1
Stay ← Stay - 10
As long as
Nb5E←0
If Reste >= 5
Nb5E←1
Remaining ← Remaining - 5

FinSi
Change given:
10 E banknotes:
Write '5 Euro notes: ', Number5E
Coins of 1 E: , remaining
End

Exercise 5.10
Spontaneously, one is tempted to write the following algorithm:
Variables N, P, i, Numé, Déno1, Déno2 in Integer
Enter the number of participating horses:
LireN
Enter the number of horses played:
ReadP
Numé←1
Pouri from 2 to N

Numé←Numé * i
Next
Den1←1
Pouri←2 to N-P
Den01←Den01 * i
Next
Den02←1

[Link]
24

Pouri←2 to P
Déno2 ← Déno2 * i
Next
Write "In order, one chance out of ", Numé / Denom1
Write 'In disorder, one over ', Numé / (Denom1 * Denom2)
End
This version, formally correct, nonetheless has two weaknesses.

The first, and most serious, concerns the way it calculates the final result. This result is the
the quotient of one number by another; now, these numbers will quickly tend to be very
large. By calculating as we do here, first the numerator, then the denominator, we
take the risk of asking the machine to store numbers too large for it to be
capable of coding them (see the preamble). It is even more foolish because nothing compels us to proceed
thus: we are not required to go through the division of two very large numbers to obtain the
desired result.

The second remark is that we have programmed three successive loops here. However, upon closer inspection,
one can see that after simplifying the formula, these three loops have the same number of
tours! (if you don't believe me, write an example of calculation and cross out the identical numbers)
numerator and denominator). This triple calculation (these three loops) can thus be reduced to
a single one. And there you have it, which is not only much shorter, but also more efficient:
Variables N, P, i, O, Fen Integer
Debut
Enter the number of participating horses:
LireN
Enter the number of horses played:
ReadP
A←1
B←1
Pouri←1 to P
A ← A * (i + N - P)
B←B*i
Following
Write "In order, one chance out of ", A
Write "In disorder, one chance out of ", A / B
End

PART 6
Exercises
Exercise 6.1

Write an algorithm that declares and fills an array of 7 numerical values by placing them
all to zero.

Exercise 6.2

[Link]
25

Write an algorithm that declares and fills an array containing the six vowels of the alphabet.
Latin.

Exercise 6.3

Write an algorithm that declares an array of 9 grades, which then prompts the user to enter the values.
the user.

Exercise 6.4
What does the following algorithm produce?

ArrayNb(5) in Integer
Integer Variables
Start
Pouri←0 to 5
Nb(i)←i * i
following
Pouri←0 to 5
WriteNb(i)
following
End
Can we simplify this algorithm while achieving the same result?

Exercise 6.5
What does the following algorithm produce?

TableauN(6) in Integer
Variables, which Integer
Beginning

N(0)←1
Pourk←1 to 6
N(k) = N(k-1) + 2
Next
Pouri←0 to 6
WriteN(i)
following
End
Can we simplify this algorithm while achieving the same result?

Exercise 6.6
What does the following algorithm produce?

Tableau Suite (7) in Full


Integer variables
Start
Suite(0)←1
Suite(1)←1

[Link]
26

Pouri←2 to 7
Sequence(i)←Sequence(i-1) + Sequence(i-2)
following
Pouri←0 to 7
WriteNext(i)
following
End

Exercise 6.7

Write the end of algorithm 6.3 so that the calculation of the average grades is performed and displayed.
on the screen.

Exercise 6.8

Write an algorithm that allows the user to input any number of values that
must be stored in an array. The user must therefore start by entering the number of
values that he intends to enter. He will then proceed with this entry. Finally, once the entry is complete, the
The program will display the number of negative values and the number of positive values.

Exercise 6.9

Write an algorithm that calculates the sum of the values in an array (assuming the array has been
previously entered).

Exercise 6.10

Write an algorithm that creates an array from two arrays of the same length
previously entered. The new table will be the sum of the elements of the two starting tables.
Table 1:

4 8 7 9 1 5 4 6

Table 2:

7 6 5 2 1 3 7 4

Table to be constituted:

11 14 12 11 2 8 11 10

Exercise 6.11

Always based on two previously entered tables, write an algorithm that calculates the
smurf of the two tables. To calculate the smurf, you need to multiply each element of the
table 1 for each element of table 2, and add them all together. For example, if we have:

[Link]
27

Table 1:

4 8 7 12

Table 2:

3 6

The Smurf will be:


3 * 4 + 3 * 8 + 3 * 7 + 3 * 12 + 6 * 4 + 6 * 8 + 6 * 7 + 6 * 12 = 279

Exercise 6.12

Write an algorithm that allows the input of any number of values, based on the principle of
the ex 6.8. All the values must then be increased by 1, and the new array will be
displayed on the screen.

Exercise 6.13

Write an algorithm that allows the user to enter a number, following the same principle.
determined values. The program, once the input is completed, returns the greatest value in
specifying which position it occupies in the table. Care will be taken to enter the data in a
first time, and the search for the greatest value of the array second.

Exercise 6.14

Always and again on the same principle, write an algorithm allowing the user to enter
the grades of a class. The program, once the input is complete, returns the number of these grades
above the class average.

Corrected Exercises
Exercise 6.1
TableauTruc(6) in Digital
Numerical Variables
Debut
Pouri from 0 to 6

Truc(i)←0

[Link]
28

Following
End

Exercise 6.2
TableauTruc(5) in Character
Debut
a
e
i
o
u
y
End

Exercise 6.3
TableauNotes(8) in Digital
Numerical Variables
Pouri from 0 to 8

Write 'Enter grade number ', i + 1


ReadNotes(i)
Following
End

Exercise 6.4
This algorithm fills an array with six values: 0, 1, 4, 9, 16, 25.
He then writes them on the screen. Simplification:
TableauNb(5) in Numeric
Numeric Variables
Start
Pouri←0 to 5
Nb(i) = i * i
WriteNumber(i)
Next
End

Exercise 6.5
This algorithm fills an array with the seven values: 1, 3, 5, 7, 9, 11, 13.
He then writes them on the screen. Simplification:
TableauN(6) in Numeric
Variables, said Digital
Start
N(0)←1
WriteN(0)
Pourk from 1 to 6

N(k) = N(k-1) + 2
WriteN(k)
Next
End

Exercise 6.6
This algorithm fills an array with 8 values: 1, 1, 2, 3, 5, 8, 13, 21

Exercise 6.7
Variable Digital
TableauNotes(8) in Digital

[Link]
29

Debut
s←0
Pouri←0 to 8
Write "Enter the grade no. ", i + 1
ReadNotes(i)
s ← s + Notes(i)
Next
Write "Average:", s/9
End

Exercise 6.8
Number of Variables
TableauT() in Numeric
Debut
Enter the number of values:
ReadNb
RedimT(Nb-1)
Nbpos←0
Nbneg←0
Pouri←0 to Nb - 1
Write "Enter number n° ", i + 1
ReadT(i)
If SiT(i) > 0 then
Nbpos←Nbpos + 1
Otherwise

Nbneg←Nbneg + 1
Finish
Following
Number of positive values:
Number of negative values:
End

Exercise 6.9
Variables, Sum, In Numerical
Table in Numeric
Debut
... (the entry of the table is not programmed, which is assumed to have N elements)
RedimT(N-1)

Som←0
Pouri from 0 to N - 1
Som←Som + T(i)
Following
Sum of the elements of the array:
End

Exercise 6.10
Variables, Digital Nene
TableauT1(), T2(), T3() in Numeric
Debut
... (it is assumed that T1 and T2 have N elements and that they are already entered)
RedimT3(N-1)

Pouri←0 to N - 1
T3(i)←T1(i) + T2(i)

[Link]
30

Following
End

Exercise 6.11
Variables i, j, N1, N2, Digital Sign
Table T1(), T2() in Digital
Debut
We do not program the input of arrays T1 and T2.
It is assumed that T1 has N1 elements, and that T2 has T2.

S←0
Pouri←0 to N1 – 1
For j = 0 to N2 - 1
S←S + T1(i) * T2(j)
Next
Next
Write "The Smurf is: ", S
End

Exercise 6.12
Variable Nb, in Numeric
Tableau T in Numeric
Debut
Enter the number of values:
ReadNb
RedimT(Nb-1)
For i = 0 to Nb - 1
Write "Enter number No. ", i + 1
Read T(i)
Next
New table:
For i = 0 to Nb - 1
T(i)←T(i) + 1
WriteT(i)
Next
End

Exercise 6.13
VariablesNb, Maximum Position Numeric
Tableau T in Numeric
Enter the number of values:
ReadNb
RedimT(Nb-1)
For i←0 to Nb - 1
Write "Enter number n° ", i + 1
ReadT(i)
Next
Posmaxi←0
For i from 0 to Nb - 1
If SiT(i) > T(Posmaxi) then
Posmaxi←i
Finish
Next
Write "Largest element: ", T(Posmaxi)

[Link]
31

Write "Position of this element: ", Posmaxi


End

Exercise 6.14
Number of Variables
TableauT() in Numeric
Debut
Enter the number of notes to be entered:
LireNb
RedimT(Nb-1)
For i from 0 to Nb - 1
Write 'Enter number n° ', i + 1
ReadT(i)
Next
Som←0
For i from 0 to Nb - 1
Som←Som + T(i)
Next
Moy←Som / Nb
NbSup←0
For i←0 to Nb - 1
If Sit(i) > Average Then
NbSup←NbSup + 1
FinSi
Next
Number of students exceeding the class average
End

PART 7
Exercises
Exercise 7.1

Write an algorithm that allows to input any number of values, and sorts them.
little by little in a table. The program, once the input is completed, should indicate whether the
elements of the table are all consecutive or not.

[Link]
32

For example, if the table is:

12 13 14 15 16 17 18

These elements are all consecutive. However, if the array is:

9 10 11 15 16 17 18

These elements are not all consecutive.

Exercise 7.2

Write an algorithm that sorts an array in descending order.


You will of course write two versions of this algorithm, one using insertion sort,
the other bubble sort.

Exercise 7.3

Write an algorithm that reverses the order of the elements of an array which we assume has been
previously entered ('the first shall be last...')

Exercise 7.4

Write an algorithm that allows the user to remove a value from an array
previously entered. The user will provide the index of the value they wish to delete. Note,
It is not about resetting a value to zero, but rather about removing it from the array itself.
! If the starting table was:

12 8 4 45 64 9 2

And if the user wants to remove the value at index 4, the new array will be:

12 8 4 45 9 2

Exercise 7.5

Write the algorithm that searches for a word entered from the keyboard in a dictionary. The dictionary is
supposed to be coded in a previously filled and sorted array.

Corrected Exercises
Exercise 7.1

[Link]
33

VariablesNb, one Integer


Boolean Flag Variable
Array of Integers
Debut
Enter the number of values:
LireNb
RedimT(Nb-1)
For i from 0 to Nb - 1
Write "Enter the number n° ", i + 1
ReadT(i)
Following
Flag←True
Pouri←1 to Nb - 1
If SiT(i) is not equal to T(i - 1) plus 1 Then

False
FinSi
Next
IfFlagThen
The numbers are consecutive.
Otherwise

The numbers are not consecutive.


FinSi
End
This programming is undoubtedly the most spontaneous, but it has the flaw of examining the
the entirety of the table, even when we discover from the beginning two non-consecutive elements. Also,
in the case of a large table, is it time-consuming to process. Another way to
the procedure would be to break out of the loop as soon as two non-consecutive elements are detected.
the second part of the algorithm would therefore become:
i←1
TantQueT(i) = T(i - 1) + 1 and i < Nb - 1
i←i + 1
As long as
SiT(i) = T(i - 1) + 1Then
The numbers are consecutive
Otherwise

The numbers are not consecutive.


FinSi

Exercise 7.2
We assume that N is the number of elements in the array. Insertion sort:

Pouri←0 to N - 2
i
For j = 1 to N - 1
If Sit(j) > t(posmaxi) then
posmaxi←j
Finished
following
temp ← t(posmaxi)
t(posmaxi) ← t(i)
t(i)←temp
following
End
Bubble sorting:

[Link]
34


Indeed
As long as there is permission

Fake
Pouri from 0 to N - 2
If Sit(i) < t(i + 1) Then
temp←t(i)
t(i)←t(i + 1)
t(i + 1) ← temp
True
Finish
following
As long as
Fin

Exercise 7.3
It is assumed that n is the number of elements in the previously entered array.

Pouri from 0 to (N-1)/2
Temp←T(i)
T(i) ← T(N-1-i)
T(N-1-i)←Temp
following
End

Exercise 7.4

Rank of the value to be deleted?
ReadS
Pouri to N-2
T(i)←T(i+1)
subsequent
RedimT(N–1)
End

Exercise 7.5
N is the number of elements in the array Dico(), containing the words of the dictionary, array
pre-filled.
Sup
Boolean Finite Variables
Start
Enter the word to verify
ReadWord
We define the boundaries of the part of the table to consider.
Sup←N - 1
Inf←0
False
As Long As Not Finished

Comp designates the index of the element to be compared. It is important to ensure that Comp
It should be a whole number, which can be done in different ways depending on the languages.
Comp←(Sup + Inf)/2
If the word is located before the comparison point, then the upper bound changes, the lower bound
the lower one does not move.

[Link]
35

IfMot < Dico(Comp)Then


Sup←Comp - 1
Otherwise, it's the opposite
Otherwise

Inf = Comp + 1
FinSi
Finish←Word = Dictionary(Comp) or Sup < Inf
As long as
IfMot = Dico(Comp)Then
the word exists
Otherwise

It does not exist


Finish
End

PART 8
Exercises Enoncedes
Exercise 8.1

Write an algorithm that fills a 6 by 13 array with zeros.

[Link]
36

Exercise 8.2

What result will this algorithm produce?


TableauX(1, 2) in Integer
Variables i, j, value Integer
Start
Val←1
Pouri←0 to 1
Forj←0 to 2
X(i, j)←Value
Val←Val + 1
Next
next
Pouri←0 to 1
Pourj←0 to 2
WriteX(i, j)
Next
Following
End

Exercise 8.3

What result will this algorithm produce?


TableauX(1, 2) in Integer
Variables i, j, value Integer
Beginning

Val←1
Pouri←0 to 1
Forj←0 to 2
X(i, j)←Val
Val←Val + 1
Next
Next
Forj←0 to 2
Pouri←0 to 1
Write X(i, j)
Next
Next
End

Exercise 8.4

What result will this algorithm produce?


TableauT(3, 1) in Integer
Variablesk, m, an Integer
Start
Pourk←0 to 3
Pourm←0 to 1
T(k, m)←k + m
Next
Next
Pourk←0 to 3
Pour 0 to 1

[Link]
37

WriteT(k, m)
Next
kNext
End

Exercise 8.5

Same questions, replacing the line:


T(k, m)←k + m

by
T(k, m) equals 2 times k plus (m plus 1)

then by:
(k + 1) + 4 * m

Exercise 8.6

Let T be a two-dimensional array (12, 8) previously filled with numerical values.


Write an algorithm that searches for the largest value within this array.

Exercise 8.7

Write a very simplified checkers game algorithm.


The computer asks the user in which square their pawn is located (which row, which
column). We set up an input control to check the validity of the entered values.
Then, we ask the user what movement they want to make: 0 (top left), 1 (to the right)
top right), 2 (bottom left), 3 (bottom right).
If the movement is impossible (i.e. we go off the board), we notify the user and stop.
there. Otherwise, we move the pawn and display the resulting checkerboard, showing an 'O' for a square.
see and an 'X' for the square where the pawn is located.

Corrected Exercises
Exercise 8.1
TableauTruc(5, 12) in Integer
Debut
Pouri←0 to 5
Forj←0 to 12
Truc(i, j)←0

[Link]
38

Next
Next
End

Exercise 8.2
This algorithm fills an array in the following way:
X(0, 0) = 1
X(0, 1) = 2
X(0, 2) = 3
X(1, 0) = 4
X(1, 1) = 5
X(1, 2) = 6
He then writes these values on the screen, in this order.

Exercise 8.3
This algorithm fills an array in the following way:
X(0, 0) = 1
X(1, 0) = 4
X(0, 1) = 2
X(1, 1) = 5
3
X(1, 2) = 6
He then writes these values to the screen, in this order.

Exercise 8.4
This algorithm fills an array in the following way:
T(0, 0) = 0
T(0, 1) = 1
1
T(1, 1) = 2
T(2, 0) = 2
3
T(3, 0) = 3
T(3, 1) = 4
He then writes these values on the screen, in this order.

Exercise 8.5
Version a: this algorithm fills an array in the following way:
1
T(0, 1) = 2
T(1, 0) = 3
T(1, 1) = 4
T(2, 0) = 5
6
T(3, 0) = 7
T(3, 1) = 8
He then writes these values to the screen, in this order.

Version b: this algorithm fills an array as follows:


1
5
T(1, 0) = 2
T(1, 1) = 6
T(2, 0) = 3

[Link]
39

T(2, 1) = 7
T(3, 0) = 4
T(3, 1) = 8
He then writes these values to the screen, in this order.

Exercise 8.6
Variables i, j, iMax, jMax in Numerical
TableauT(12, 8) in Numeric
The principle of searching in a two-dimensional array is strictly the same as in a
one-dimensional table, which should not surprise us. The only thing that changes is that here the
Balayage requires two nested loops, instead of just one.
Debut
...
iMax←0
jMax←0
Pouri from 0 to 12

Pourj←0 to 8
If SiT(i,j) > T(iMax,jMax) Then
iMax ← i
jMax ← j
Finally
Next
Next
Write "The largest element is ", T(iMax, jMax)
It is located at the indices
End

Exercise 8.7
Variables i, j, posi, posj, i2, j2 as Integer
Correct variables, MoveOKen Boolean
Checkerboard(7, 7) in Boolean
TableauMouv(3, 1) in Integer
The checkerboard containing a single pawn, we choose to code it economically by representing it by a
two-dimensional boolean table. In each of the slots of this checkerboard, False means
the absence of the pawn, True its presence.

Furthermore, a nasty trick is used, not mandatory, but very practical in many
situations. The idea is to match the possible choices of the user with the movements
the pawn. We then enter into a two-dimensional Mouv table, the movements of the pawn according to
four directions, ensuring that each line of the table corresponds to an entry of
the user. The first value is the displacement in i, the second the displacement in j. This
will spare us from having to do the same tests four times afterwards.
Debut
Choice 0: pawn at the top right
Move(0, 0)←-1
Mouv(0, 1)←-1
Choice 1: pawn at the top right
Mouv(1, 0)←-1
Move(1, 1)←1
Choice 2: pawn in the bottom left
Move(2, 0)←1
Mouv(2, 1) ← -1
Choice 3: pawn at the bottom right

[Link]
40

Move(3, 0)←1
Mouv(3, 1)←1
Initialization of the board; the piece is currently nowhere.
Pouri←0 to 7
Forj←0 to 7
Damier(i, j)←False
following
following
Input the coordinate in i ("posi") with input validation
Correct←False
As long as it's not correct

Enter the line of your pawn:


Lireposi
If siposi >= 0 and posi <= 7 Then
Correct
Finish
Finishing
Input of the coordinate in j ('posj') with input validation
Correct←False
As long as it's not correct

Enter the column of your pawn:


Lireposj
If Siposj >= 0 and posj <= 7 Then
True
Finish
Fintantque
Positioning of the pawn on the virtual checkerboard.
Checker(posi, posj) ← True
Entry of the movement, with control
What movement?
Write" - 0: top left
Write - 1: at the top right
Write - 2: bottom left
Write - 3: bottom right
False
As long as it's not correct

ReadDep
If SiDep >= 0 and Dep <= 3 Then
True
FinSi
As long as
i2 and j2 are the future coordinates of the pawn. The boolean variable MoveOK checks the validity of this
future location
i2←posi + Move(Dep, 0)
j2←posj + Move(Dep, 1)
MoveOK←i2 >= 0 and i2 <= 7 and j2 >= 0 and j2 <= 7
Case where the movement is valid
IfMoveOKThen
False
Checker(i2, j2)←True
Display of the new checkerboard
Pouri←0 to 7
Forj←0 to 7
IfDamier(i, j) Then

[Link]
41

Write 'O';
Otherwise

Write " X ";


FinSi
following
Write"
next
Otherwise

Case where the move is not valid


Impossible movement
FinSi
End

PART 9
Exercise Statements
Exercise 9.1

Among these assignments (considered independently of each other), which ones will cause
errors, and why?
Variables A, B, C in Numeric
Variables D, E in Character
A ← Sin(B)
A←Sin(A + B * C)
B ← Sin(A) – Sin(D)

[Link]
42

D←Sin(A / B)
C ← Cos(Sin(A)

Exercise 9.2

Write an algorithm that asks the user for a word and displays on the screen the number of
letters of this word (it's really very simple).

Exercise 9.3

Write an algorithm that asks the user for a sentence and displays the number of
words of this sentence. It is assumed that the words are only separated by spaces (and that is already
a little less stupid).

Exercise 9.4

Write an algorithm that asks the user for a sentence and displays the number of
vowels contained in this sentence.
We will be able to write two solutions. The first deploys a rather tedious compound condition. The
Secondly, using the Find function significantly lightens the algorithm.

Exercise 9.5

Write an algorithm that asks the user for a sentence. The user will then enter the rank of a
character to be removed, and the new sentence must be displayed (we must actually remove the
character in the variable that stores the phrase, and not just on the screen.

Exercise 9.6 - Cryptography 1

One of the oldest systems of cryptography (easily decipherable) consists of shifting the letters.
of a message to make it unreadable. Thus, A becomes B, B becomes C, etc. Write a
algorithm that asks the user for a sentence and encodes it according to this principle. As in the
in the previous case, the encoding should be done at the level of the variable storing the phrase, and not
only on the screen.

Exercise 9.7 - Cryptography 2 - the Caesar cipher

A (relative) improvement of the previous principle consists in operating with a shift not of 1,
more than any number of letters. Thus, for example, if one chooses a shift of 12, the A
become M, the B become N, etc.
Create an algorithm on the same principle as the previous one, but which additionally asks what is the
shift to use. Your proverbial sense of elegance will of course forbid you a series of twenty-six
Yes...So

Exercise 9.8 - Cryptography 3

[Link]
43

A subsequent technique of cryptography involved operating not with a systematic shift,


but by a random substitution. For this, a key alphabet is used, in which the letters
succeed in a disorderly manner, for example:
HYLUJPVREAKBNDOFSQZCWMGITX
It is this key that will then be used to encode the message. According to our example, the A's will become
H, the B of Y, the C of L, etc.
Write an algorithm that performs this encryption (the key alphabet will be input by the user, and we
provided he makes a correct input).

Exercise 9.9 - Cryptography 4 - the Vigenère cipher

A cryptography system much harder to break than previous ones was invented in the 16th century.
century by the French Vigenère. It consisted of a combination of different Caesar ciphers.
Indeed, we can write 25 shifted alphabets compared to the normal alphabet:

• the alphabet that starts with B and ends with ...YZA


• the alphabet that starts with C and ends with ...ZAB
• etc.

The encoding will be based on the principle of the Caesar cipher: the original letter is replaced by the
letter occupying the same place in the shifted alphabet.
But unlike Caesar's cipher, the same message will use not one, but several.
shifted alphabets. To know which alphabets should be used, and in what order, one uses
a key.
If this key is 'VIGENERE' and the message is 'We must encode this phrase', we will proceed as follows:
The first letter of the message, I, is the 9th letter of the normal alphabet. It must be encoded in
using the alphabet starting with the first letter of the key, V. In this alphabet, the 9th letter
is the D. I thus becomes D.
The second letter of the message, L, is the 12th letter of the normal alphabet. It should be coded in
using the alphabet starting with the second letter of the key, I. In this alphabet, the 12th letter
is L. So it becomes S, etc.
When we reach the last letter of the key, we start again at the first.
Write the algorithm that performs a Vigenère encryption, of course asking for the key at the beginning.
the user.

Exercise 9.10
Write an algorithm that asks the user for an integer. The computer then displays the
This number is even

Exercise 9.11
Write the algorithms that generate a random Glup number such that ...

• 0 <= Glup < 2


• -1 <= Glup < 1

[Link]
44

• 1.35 <= Glup < 1.65


• Glup emulates a six-sided die
• -10.5 <= Glup < +6.5
• Glup emulates the sum of the simultaneous roll of two six-sided dice.

Corrected Exercises
Exercise 9.1
A←Sin(B) No problem
A ← Sin(A + B * C) No problem
B←Sin(A) – Sin(D) Error! D is in character
D←Sin(A / B) No problem... if B is different from zero
C←Cos(Sin(A) Error! A closing parenthesis is missing.

Exercise 9.2
You were warned, it's as simple as that! You just need to use the Len function, and it's done:
Variable Moten Character
VariableNben Integer
Debut
Enter a word:
ReadWord
Nb ← Len(Word)
Write "This word has ", Nb, " letters"
End

Exercise 9.3
There, we have to count the number of spaces in the sentence using a loop, and we
deduce the number of words. The loop examines the characters of the sentence one by one.
one, from first to last, and compares them to space.
VariableBlaen Character
VariablesNb, is an Integer
Debut
Write "Enter a sentence: "
LireBla
Nb←0
For i = 1 to Len(Bla)
If Mid(Bla, i, 1) = ' ' Then
Nb ← Nb + 1
FinSi
following
Write "This sentence contains ", Nb + 1, " words"
End

Exercise 9.4
Solution 1: for each character of the word, we impose a very painful compound condition. The
Less than one can say, this choice is not distinguished by its elegance. That said, it
so it works, after all, why not.
VariableBlaen Character
VariablesNb, i, in Integer
Debut
Write 'Enter a sentence: '
LireBla
Nb←0
For i = 1 to Len(Bla)

[Link]
45

If Mid(Bla, i, 1) = "a" or Mid(Bla, i, 1) = "e" or Mid(Bla, i, 1) = "i" or


Mid(Bla, i, 1) = "o" or Mid(Bla, i, 1) = "u" or Mid(Bla, i, 1) = "y" Then
Nb←Nb + 1
Finish
following
Write "This sentence has ", Nb, " vowels"
End
Solution 2: we store all the vowels in a string. Using the Find function, we detect
immediately if the examined character is a vowel or not. It's clearly more pleasant...
VariablesBla, Voyen Character
VariablesNb, i, are Integer
Debut
Write 'Enter a sentence: '
LireBla
Nb←0
aeiouy
For i←1 to Len(Bla)
If Find(Voy, Mid(Bla, i, 1)) <> 0 Then
Nb←Nb + 1
FinSi
following
Write "This sentence has ", Nb, " vowels"
End

Exercise 9.5
There is no way to directly remove a character from a string... other than by
proceeding by concatenation. Therefore, it is necessary to concatenate what is on the left of the character to be deleted,
with what is to its right. Pay attention to the parameters of the Mid functions, they have nothing
obvious!
VariableBlaen Character
VariablesNb, i, in Integer
Start
Write 'Enter a sentence: '
ReadBla
Enter the position of the character to delete:
ReadNb
L←Len(Bla)
Bla←Mid(Bla, 1, Nb – 1) & Mid(Bla, Nb + 1, L – Nb)
The new sentence is:
End

Exercise 9.6
Among all the exercises in cryptography, there are two main possible strategies:

- either convert the characters to their ASCII codes. The algorithm then amounts to processing
numbers. Once these numbers are transformed, they need to be converted back into characters.

either remain at the character level and proceed directly with the transformations at this level.
It is this last option that is chosen here, and for all upcoming cryptography exercises.

For this exercise, there is a general rule: for each letter, we detect its position in
the alphabet, and it is replaced by the letter occupying the following position. Only special case, the

[Link]
46

the twenty-sixth letter (the Z) must be coded by the first (the A), and not by the twenty-seventh, which
does not exist!
VariablesBla, Cod, Alpha in Character
Entire Posen Variables
Beginning

Write 'Enter the phrase to encode: '


LireBla
ABCDEFGHIJKLMNOPQRSTUVWXYZ

For i ← 1 to Len(Bla)
Let ← Mid(Bla, i, 1)
If Let <> "Z" Then
Pos←Find(Alpha, Let)
Cod←Cod & Mid(Alpha, Pos + 1, 1)
Otherwise

Cod←Cod & "A"


FinSi
Next
Bla←Cod
The coded phrase is:
End

Exercise 9.7
This algorithm is a generalization of the previous one. But here, as we do not know in advance the
offset to apply, we do not know in advance how many 'special cases', namely exceedances
beyond the Z, there will be.
So we need to find a simple way to say that if we get 27, we actually have to take the letter.
number 1 of the alphabet, that if you get 28, you should actually take number 2, etc. This means
It is simple: you need to consider the remainder of the division by 26, in other words, the modulo.
There is an additional small trick to apply, as 26 must remain 26 and not become 0.
VariableBla, Code, Alphabet Character
Variables, Position, Integer Offset
Beginning

Enter the offset to apply:


ReadShift
Enter the phrase to encode:
LireBla
Alpha←"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

For i←1 to Len(Bla)


Let ← Mid(Bla, i, 1)
Pos ← Find(Alpha, Let)
NewPos ← Mod(Pos + Shift, 26)
If New Position = 0 Then
NouvPos←26
FinSi
Cod←Cod & Mid(Alpha, NouvPos, 1)
Next
Bla←Cod
Write "The coded sentence is: ", Bla
End

Exercise 9.8
There, it's quite straightforward.

[Link]
47

VariableBla, Code, Alphabet Character


Variables, Position, Shift Integer
Start
Write 'Enter the key alphabet: '
ReadKey
Enter the phrase to encode:
ReadBla
Alpha="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

For i from 1 to Len(Bla)


Let ← Mid(Bla, i, 1)
Pos←Find(Alpha, Let)
Cod←Cod & Mid(Key, Pos, 1)
Next
Bla←Cod
The coded phrase is: Bla
End

Exercise 9.9
The Vigenère cipher is not only harder to break; it is also a bit more rigid.
to program. The main difficulty is understanding that two loops are needed: one for
browse the phrase to be coded, the other to browse the key. But when we think about it, these two
loops should definitely not be nested. And in reality, no matter how one ...
the written, they form just one.
VariablesAlpha, Bla, Cod, Key, Character
Variables, Pos, KeyPos, Offset Integer
Start
Enter the key:
ReadKey
Write "Enter the phrase to encode: "
ReadBla
Alpha←"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

PosKey←0
Fori←1 to Len(Bla)
We manage the progression in the key. I did this "manually" using a loop, but a nice use.
The Modulo function would have allowed for programming in a single line!
Posclé←Posclé + 1
If PosClé > Len(Clé) Then
PosKey←1
FinSi
We determine what the key letter is and its position in the alphabet.
LetKey←Mid(Key, PosKey, 1)
PosKey ← Find(Alpha, Key)
We determine the position of the letter to be coded and the shift to apply. Once again, a solution
an alternative would have been to use Mod: that would have spared us the If...
Let←Mid(Bla, i, 1)
Pos←Find(Alpha, Let)
NewPos ← Pos + PosKeyLet
If NewPos > 26 Then
NouvPos←NouvPos - 26
FinSi
Cod←Cod & Mid(Alpha, NewPos, 1)
Following

[Link]
48

Bla←Cod
The coded phrase is:
End

Exercise 9.10
We're getting back to simpler things...
Variable N is Integer
Enter your number:
ReadNb
SiNb/2 = Ent(Nb/2)Then
This number is even
Otherwise

This number is even


FinSi
End

Exercise 9.11
a) Glup←Alea() * 2
b) Glup←Alea() * 2 - 1
c) Glup←Alea() * 0.30 + 1.35
d) Glup←Ent(Random() * 6) + 1
e) Glup←Alea() * 17 - 10.5
f) Glup ← Ent(Alea() * 6) + Ent(Alea() * 6) + 2

PART 10
Statement of Exercises
Exercise 10.1

What result does this algorithm produce?


VariableTrucen Character
Beginning

Open "[Link]" for reading


As long as Not EOF(5)
ReadFile5, Trick
WriteThing

[Link]
49

As long as
Close5
End

Exercise 10.2

Write the algorithm that produces a result similar to the previous one, but the text file
"[Link]" is once again of delimited type (delimiter character: /). We will produce on the screen
a display where for aesthetic reasons, this character will be replaced with spaces.

Exercise 10.3

We work with the address book file in fixed-width fields.


Write an algorithm that allows the user to enter a new individual via the keyboard.
added to this address book.
-

Exercise 10.4

Same question, but this time the notebook is supposed to be sorted alphabetically. The individual
must therefore be inserted in the right place in the file.

Exercise 10.5

Write an algorithm that allows you to modify a piece of information (to simplify, let's say
only the last name) of a member of the address book. You must therefore ask for
the user what is the name to be modified, then what is the new name, and update the file. If
The searched name does not exist, the program must report it.

Exercise 10.6

Write an algorithm that sorts the individuals in the address book in alphabetical order.

Exercise 10.7

Let [Link] and [Link] be two files whose records have the same structure. Write a
algorithm that copies the entire file Toto into the file Tutu, and then appends the entire file Tata
(file concatenation).

Exercise 10.8

Write an algorithm that removes from our address book all individuals whose email is
invalid (to use a simple criterion, we will consider that emails that do not
containing no at sign, or more than one at sign).

[Link]
50

Exercise 10.9

The records of a file contain two fields Name (string) and


Amount (Integer). Each record corresponds to a sale completed by a salesperson of a
society.
We want to record in a table, then display on the screen, the total sales by salesperson. For
To simplify, we assume that the initial file is already sorted alphabetically by seller.

Exercise Solutions
Exercise 10.1
This algorithm writes the entire file "[Link]" to the screen.

Exercise 10.2
VariableTrucen Character
Integer Variables
Debut
Open '[Link]' in read mode
As long as not EOF(5)
ReadFile5, Thing
For i = 1 to Len(Thing)
IfMid(Truc, i, 1) = "/" Then
Write
Otherwise

WriteMid(Thing, i, 1)
FinSi
Following
As long as
Close5

Exercise 10.3
VariablesNom * 20, Prénom * 17, Tel * 10, Mail * 20, Ligen Caractère
Debut
Enter the name:
ReadName
Enter the first name:
ReadFirstName
Enter the phone number:
LireTel
Enter the name:
LireMail
Line
Open '[Link]' for Append
WriteFile1, Line
Close1
End

Exercise 10.4
There, as indicated in the course, we go through an array of structures in RAM, which is
the technique most frequently employed. The sorting - which is actually a simple test - will be carried out.
on the first field (name).
StructureBottin
Name Character* 20

[Link]
51

First Name Character* 15


Telen Character* 10
Mailen Character* 20
Fin Structure
Tableau Mespotes() in Directory
Variables MyBuddy, New in Directory
Variables, just Numeric
Debut
Enter the name:
[Link]
Enter the first name:
[Link]
Enter the phone:
[Link]
Enter the email:
Read New Mail
We copy the entirety of "Addresses" into MyFriends(). And after all, it's the opportunity: when we
falls in the right place, we sneak our new friend into the table.
Open "[Link]" on 1 for Reading
i←-1
inserted←False
As long as Not EOF(1)
i←i + 1
RedimMyFriends(i)
ReadFile1, MyBuddy
[Link] > [Link] and Not InsertedThen
New
Inserted←True
i←i+1
RedimMyFriends(i)
Finish
MyFriend(i)←MyFriend
As long as
Close1
And the tour is almost done. All that remains is to rebalance the entire table as is.
MyFriends in the file, overwriting the old version.
Open "[Link]" on 1 for Writing
Forj←0 to i
WriteFile1, MyFriends(j)
following
Close1
End

Exercise 10.5
It's a bit of the same ilk as what we've just done, with a few variations.
essentially a small flag management for good measure.
Structure Directory
Name Character* 20
Character* 15
Telecharacter* 10
Mail Character* 20
Fin Structure
Tableau of My Spots in Directory

[Link]
52

Variables My Buddy in the Directory

Old, New in Character*20


Variables, only Numeric
Variable Found in Boolean
Debut
Enter the name to modify:
Read Old
Enter the new name:
ReadNew
We copy the entirety of 'Addresses' into Fic, while searching for the clampin. If we find it, we
make the modification.
Open "[Link]" for Reading
i←-1
Found←False
As long as Not EOF(1)
i←i+1
RedimMyFriends(i)
ReadFile1, MyBuddy
[Link]
Found←True
New
FinSi
MyFriends(i) ← MyFriend
FinTantQue
Close1
We then copy the entire Fic into "Address".
Open "[Link]" for Writing
For j = 0 to i
WriteFile1, MyFriends(j)
Next
Close1
And a little message to finish!
IfFoundThen
Modification made
Otherwise

Unknown name. No changes made.


FinSi
End

Exercise 10.6
There, it's a sort on an array of structures, nothing easier. And we are very happy to have.
structures, in other words, to deal with only a single table...
Structure Directory Name Character* 20
Character* 15
Tele character* 10
Mail Character* 20
Fin Structure
Table of my spots in the Directory
Variables Miniature Guide
Variables, only Numeric
Debut

[Link]
53

We copy the entire 'Addresses' into MyFriends...


Open '[Link]' for Reading
i←-1
TantqueNot EOF(1)
i←i+1
RedimMyFriends(i)
ReadFile1, MyFriends(i)
As long as
Shut down1
We sort the array using the insertion sort algorithm already studied, using the Name field.
the structure:
For j = 0 to i - 1
Mini←MyFriends(j)
posmini←j
Pourk←j + 1 to i
IfMyFriends(k).Name < [Link]
mini←MyFriends(k)
posmini←k
Done
ksuivant
MyFriends(posmini)←MyFriends(j)
MyFriends(j)←Mini
following
We then copy the entire table into 'Address'.
Open "[Link]" for Writing
For j from 0 to i

WriteFile1, MyFriends(j)
following
Close1
End

Exercise 10.7
Well, this one is so stupid that we don't even need to go through arrays in memory.
live.
Variable Character
Beginning

Open "[Link]" for append


Open "[Link]" for Reading
As long as not EOF(2)
ReadFile2, Line
WriteFile1, Line
As long as
Close2
Open "[Link]" on 3 for Reading
As long as not EOF(3)
ReadFile2, Line
WriteFile1, Line
As long as
Close3
Close1
End

Exercise 10.8
We will eliminate the bad entries right from the copy: if the record does not have an email
valid, we ignore it, otherwise we copy it into the table.

[Link]
54

Structure Directory
Name Character* 20
First name Character* 15
Send character* 10
Mail Character* 20
Fin Structure
TableauMespotes() in Directory
Variable My Buddy Phone Directory

Variables, just Numerical


Debut
We are copying "Addresses" into MyFriends while testing the email...
Open "[Link]" for Reading
i←-1
As long as not EOF(1)
ReadFile1, MyBuddy
nb←0
For i from 1 to Len([Link])
If Mid([Link], i, 1) = "@" Then
nb ← nb + 1
FinSi
following
Sinb = 1Then
i←i+1
RedimMyFriends(i)
MyFriends(i)←MyFriend
finishing

As long as
Close1
We then copy the entirety of Fic into 'Address'.
Open "[Link]" on 1 for Writing
For j←0 to i
WriteFile1, MyFriends(j)
Next
Close1
End

Exercise 10.9
Once again, going through a structure table is a convenient strategy. Attention
however, since it is a text file, everything is stored in characters. Therefore, it will be necessary to convert
in numeric format the characters representing the sales, in order to perform the requested calculations.
For the processing, there are two possibilities. Either we copy the file exactly in a first
table, and then we process this table to sum by seller. Either we do the processing
directly, from the reading of the file. This option is chosen in this correction.
Seller Structure
Nomen Caractère* 20
Digital Amount
Fin Structure
TableMySellers() to Seller
VariablesNomPrec * 20, Lig, Character name
VariablesSum, Digital Sale
We clean the file by doing our additions.
As soon as the name has changed (we moved on to the next seller), we store the result and put everything back to.
zero

[Link]
55

Debut
Open "[Link]" for Reading
i←-1
Sum←0
NomPréc
As long as Not EOF(1)
ReadFile1, Line
Name←Mid(Lig, 1, 20)
Sale←CNum(Mid(Line, 21, 10)
IfName = PreviousNameThen
Sum←Sum + Sale
Otherwise

i←i+1
RedimMesVendeurs(i)
MesVendeurs(i).Name ← PreviousName
MySellers(i).Amount ← Sum
Sum←0
FirstName ← Name
FinSi
As long as
And let’s not forget a little tour for the last of these gentlemen...
i←i+1
RedimMesVendeurs(i)
NomPrec
MySellers(i).Amount ← Sum
Close1
Finally, we display the table on the screen
For j from 0 to i

WriteMySellers(j)
following
End

PART 11
Statement of Exercises
Exercise 11.1

Write a function that returns the sum of five numbers provided as arguments.

Exercise 11.2

[Link]
56

Write a function that returns the number of vowels contained in a string.


passed as an argument. By the way, note that a function is perfectly entitled to call another
function.

Exercise 11.3

Rewrite the function Find, seen previously, using the Mid and Len functions (which means that,
Find, unlike Mid and Len, is not an essential function in a language.

Corrected Exercises
Exercise 11.1
Here is a gentle start...
FunctionSum(a, b, c, d, e)
Will send back + b + c + d + e
EndFunction

Exercise 11.2
FunctionNbVowels(Word in Character)
Variables, in Numeric
For i = 1 to Len(Word)
If Find("aeiouy", Mid(Word, i, 1)) <> 0 Then
nb ← nb + 1
FinSi
following
Renvoyernb
FinFunction

Exercise 11.3
FunctionFind(a, b)
Numerical Variables
Start
i←1
While < Len(a) - Len(b) and b <> Mid(a, i, Len(b))
i←i+1
As long as
Sib <> Mid(a, i, Len(b))Then
Resend0
Otherwise

Resend
EndFunction

Function ChooseWord
Some explanations: we read the entire file containing the list of words. To and fro
measure, we arrange these words in the List table, which is resized at each loop iteration. A
random drawing occurs then, which allows to return one of the words at random.
FunctionWordChoice()
TableList() in Character
Variables Number of words, Choose Numeric
Open '[Link]' in Read mode
Nbmots←-1
As long as not EOF(1)
Nbmots←Nbmots + 1

[Link]
57

ResizeList(Nbmots)
ReadFile1, List(NumberOfWords)
As long as
Close1
Choose ← Enter(Random() * NumberOfWords)

ReturnList(Chosen)
FinFunction

Function FinitePart
We start by checking the number of wrong answers, the reason for defeat. Then, we look at
if the game is won, treatment similar to Flag management: it is enough that one of the
the letters of the word to guess have not been found so that the game is not won. The function
will need, as arguments, the Verif array, its number of elements, and the current number
wrong answers.
FiniteFunction(t() in Boolean, n, x in Numeric)
Variables, issue in Numeric
Six = 10Then
Resend2
Otherwise

Issue←1
Pouri←0 to n
If not then
Issue←0
End
following
Resend Issue
FinSi
FinFunction

Procedure DisplayWord
The same loop allows us to consider one by one the letters of the word to find (variable m),
and to know whether these letters have been identified or not.
Procedure DisplayWord(men Character by Value, t() Boolean by Value)
VariableAffen Character
Variable in Numeric

For i from 0 to len(m) - 1


If not then
Aff←Aff & '-'
Otherwise

Aff←Aff & Mid(mot, i + 1, 1)


FinSi
following
WriteAff
EndProcedure
Note: this procedure could also have been written in the form of a function, which
would have returned to the main procedure the string Aff. Writing to the screen of this
the Aff chain would then have been made by the main procedure.
Here is a situation where one can quite indifferently opt for a sub-procedure or for
a function.

Procedure EnterLetter
We check that the entered sign (parameter b) is indeed a single letter, which does not appear in the
previously made proposals (parameter a)

[Link]
58

ProcedureInputLetter(a, by Reference Character)


Correct Boolean Variable
VariableAlpha as Character
Beginning

Correct←False
Alpha←"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
As long as it is not correct

Enter the proposed letter:


Read
If Find(alpha, b) = 0 Or length(b) <> 1 Then
It is not a letter!
IfFound(a, b) <> 0Then
Letter already proposed!
Otherwise

True
a is assigned the value of a and b

FinSi
As long as
End Procedure

Procedure VerifLetter
The parameters are multiplying... L is the proposed letter, t() the boolean array, M the word to
find N the number of bad proposals. There is no major difficulty in this
Procedure: we examine the letters of M one by one, and we draw the consequences. The flag serves to
to know whether the proposed letter was or was not part of the word to guess.
Procedure VerifyLetter(L, Men Character by Value, t() as Boolean by Reference, N
in Digital by Reference)
Correct Boolean Variables
Start
Correct←False
For i = 1 to Len(M)
SiMid(M, i, 1) = LThen
True
T(i - 1) ← True
FinSi
FinTantQue
If not, correct then
N←N+1
FinSi
End Procedure

Epilogue Procedure
ProcedureEpilogue(Men Character by Value, Nen Numeric by Value)
Beginning
If Sin = 2 Then
A bad proposition too many... Game over!
Write "The word to guess was: ", M
Otherwise

Write 'Bravo! You found it!'


FinSi
End Procedure

Main Procedure
Main Procedure
Variables

[Link]
59

Variables g i, Numeric MovRepen


TableauVerify() in Boolean
Start
Word←ChooseTheWord()

RedimVerif(Len(Word)-1)
For i←0 to Len(Word)-1
Verif(i)←False
following
k←0
Tantquek = 0
DisplayWord(Word, Check())
InputLetter
VerifyLetter(Letter, Word, Verify(), MoveRep)
k ← EndOfGame(Verify(), len(word), MovRep)
As long as
Epilogue(Mot, k)
End

[Link]

You might also like