As long as…
Tant que…
A loop repeats a block of instructions. while means “as long as”: as long as the condition is true, the computer runs the block between braces again.
Une boucle répète un bloc d’instructions. while veut dire « tant que » : tant que la condition est vraie, l’ordinateur exécute encore le bloc entre accolades.
Here i is 1, then 2, 3, 4, 5. When i reaches 6, the condition i <= 5 becomes false and the loop stops.
Ici, i vaut 1, puis 2, 3, 4, 5. Quand i arrive à 6, la condition i <= 5 devient fausse et la boucle s’arrête.
The for loop
La boucle for
for puts the three parts of a loop on a single line: the start (let i = 1), the condition to carry on (i <= 5), and what changes after each turn (i++, which adds 1 to i).
for rassemble les trois morceaux d’une boucle sur une seule ligne : le départ (let i = 1), la condition pour continuer (i <= 5) et ce qui change après chaque tour (i++, qui ajoute 1 à i).
Adding up
Accumuler
A loop can add numbers into a variable, one at a time. Here is the sum of all the numbers from 1 to 100. Carl Friedrich Gauss is said to have found it in his head, at the age of 8. The computer is faster, but it adds them one by one!
Une boucle peut ajouter des nombres dans une variable, un à la fois. Voici la somme de tous les nombres de 1 à 100. On raconte que Carl Friedrich Gauss l’a trouvée de tête, à 8 ans. L’ordinateur va plus vite, mais il les additionne un par un!
A condition inside a loop
Une condition dans une boucle
A loop can hold an if: at each turn, the computer decides what to do.
Une boucle peut contenir un if : à chaque tour, l’ordinateur décide quoi faire.
Exercises
Exercices
Count to ten
Compter jusqu’à dix
Print the numbers from 1 to 10, one per line, with a loop.
Affiche les nombres de 1 à 10, un par ligne, avec une boucle.
A times table
Une table de multiplication
The number t already exists. Print its times table from 1 to 10, exactly in this form (here for t = 7):
Le nombre t existe déjà. Affiche sa table de multiplication de 1 à 10, exactement sous cette forme (ici pour t = 7) :
7 x 1 = 7
7 x 2 = 14
…
7 x 10 = 70
From 1 to n
De 1 à n
Print the sum of all the whole numbers from 1 to n: 1 + 2 + 3 + … + n.
Affiche la somme de tous les nombres entiers de 1 à n : 1 + 2 + 3 + … + n.
Countdown
Le compte à rebours
Print n, then n - 1, and so on down to 1, one number per line, then Liftoff!
Affiche n, puis n - 1, et ainsi de suite jusqu’à 1, un nombre par ligne, puis Décollage!
The divisors
Les diviseurs
Print all the divisors of n, from the smallest to the biggest, one per line. A number d is a divisor of n when n % d === 0: the division leaves no remainder.
Affiche tous les diviseurs de n, du plus petit au plus grand, un par ligne. Un nombre d est un diviseur de n quand n % d === 0 : la division ne laisse pas de reste.