PSeInt while loop (Mientras) exercises
17 examples
How it works
Mientras repeats a block of instructions while a condition is true. The condition is checked before every pass: if it's already false when the loop is reached, the block doesn't run at all.
Use it when you don't know in advance how many passes there will be: keep reading numbers until someone types 0, play until the guess is right, divide a number while it's above zero.
The key is that something inside the loop changes the condition. Forget to increase the counter or to read the value again and the loop never ends. A trace table shows it right away.
Short example
The least you need to see it work. Copy it or open it in the editor.
Algoritmo SumUntilZero Definir n, suma Como Entero suma <- 0 Escribir "Type numbers (0 to stop):" Leer n Mientras n <> 0 Hacer suma <- suma + n Leer n FinMientras Escribir "The sum is ", sumaFinAlgoritmoWhat it prints:
Type numbers (0 to stop):User answer: 4User answer: 10User answer: -2User answer: 0The sum is 12
Opens in the browser editor, nothing to install.
Solved exercises
Each exercise comes with the full code, its flowchart and a sample run.
Sum Until Zero
Adds up the numbers you type until you enter a 0.
BeginnerGuess the Number
Guess a secret number from 1 to 100 in seven tries.
IntermediateLinear Search
Finds a name in a list, ignoring upper and lower case.
IntermediateBubble Sort
Sorts random numbers by swapping neighbors, and stops as soon as they're in order.
IntermediateInsertion Sort
Inserts each number among the sorted ones, like arranging cards in your hand.
IntermediateBinary Search
Finds a value in a sorted array by halving the range every step.
IntermediateLinear vs. Binary Search
Counts the comparisons each search needs on the same sorted list.
IntermediatePrime Numbers
Finds every prime number up to a limit.
IntermediateGCD and LCM
Computes the greatest common divisor and the least common multiple.
IntermediateShopping List
Adds items to a list that grows until you type FIN.
AdvancedShell Sort
Insertion sort between far-apart elements, with a gap that shrinks every pass.
AdvancedMerge Sort
Splits the array in halves, sorts each one recursively and merges them.
AdvancedHeap Sort
Arranges the array as a heap, then takes the largest out again and again.
AdvancedRoman Numerals
Converts a number from 1 to 3999 into Roman numerals.
AdvancedBase Conversion
Writes a number in binary and hexadecimal.
AdvancedTic-Tac-Toe
The classic three-in-a-row game for two players.
AdvancedHangman
Guess a secret word letter by letter, with six mistakes allowed.
Advanced
In the language reference
The instructions involved, explained one by one.
Other concepts
Codoritmo is an independent, open-source project inspired by PSeInt and compatible with its syntax. It is not affiliated with the PSeInt project. Official PSeInt website.