Loops are what turn a calculator into a program. Instead of writing the same instruction a hundred times, you write it once and tell PSeInt how many times — or until when — to repeat it. PSeInt has three loop structures, and choosing the right one makes your algorithm shorter and easier to understand:
Para(for): repeat a known number of times.Mientras(while): repeat while a condition is true, checking before each pass.Repetir … Hasta Que(repeat until): repeat until a condition becomes true, checking after each pass.
This guide explains each one, the patterns that appear in almost every exercise (counters, accumulators, maximums, validation), nested loops and the dreaded infinite loop. Run every example in the online editor and use Step to watch the loop variable change.
The Para loop
Use Para when you know — or can calculate — how many repetitions you need.
Algoritmo TablaDel7
Definir i Como Entero
Para i <- 1 Hasta 10 Con Paso 1 Hacer
Escribir "7 x ", i, " = ", 7 * i
FinPara
FinAlgoritmo
How PSeInt executes it:
- Assign the start value:
i <- 1. - If
ihas passed the end value (10), the loop ends. - Otherwise run the body, add the step to
iand go back to step 2.
Con Paso 1 is optional: without it the step is 1. Other steps are useful too:
Para i <- 0 Hasta 100 Con Paso 5 Hacer // 0, 5, 10, ..., 100
Escribir i
FinPara
Para i <- 10 Hasta 1 Con Paso -1 Hacer // cuenta regresiva
Escribir i
FinPara
i manually inside a Para makes the loop hard to follow and behaves differently between tools. If you need that kind of control, use Mientras.The Mientras loop
Mientras repeats as long as its condition is true. The condition is checked before each pass, so if it is false from the start, the body never runs.
Algoritmo DuplicarHastaMil
Definir x, pasos Como Entero
x <- 1
pasos <- 0
Mientras x < 1000 Hacer
x <- x * 2
pasos <- pasos + 1
FinMientras
Escribir "Se llegó a ", x, " en ", pasos, " pasos"
FinAlgoritmo
Here we cannot easily know the number of repetitions in advance — that's the typical signal for Mientras. The output is "Se llegó a 1024 en 10 pasos".
Every Mientras loop needs three ingredients:
- Initialisation of the variables used in the condition (
x <- 1). - The condition (
x < 1000). - An update inside the body that eventually makes the condition false (
x <- x * 2). Forget this and you get an infinite loop.
The sentinel pattern
A very common use of Mientras is reading data until the user enters a special "end" value, called a sentinel:
Algoritmo PromedioConCentinela
Definir nota, suma Como Real
Definir cantidad Como Entero
suma <- 0
cantidad <- 0
Escribir "Ingrese notas (-1 para terminar):"
Leer nota
Mientras nota <> -1 Hacer
suma <- suma + nota
cantidad <- cantidad + 1
Leer nota
FinMientras
Si cantidad > 0 Entonces
Escribir "Promedio: ", suma / cantidad
SiNo
Escribir "No se ingresaron notas"
FinSi
FinAlgoritmo
Notice the two Leer nota: one before the loop (so the condition has a value to check) and one at the end of the body (to get the next value). This "read ahead" structure is the correct way to write sentinel loops — and the final Si avoids dividing by zero when the first value is already the sentinel.
The Repetir – Hasta Que loop
Repetir checks its condition after each pass, so the body always runs at least once. It stops when the condition becomes true — the opposite of Mientras.
Algoritmo ValidarNota
Definir nota Como Real
Repetir
Escribir "Ingrese una nota entre 0 y 10:"
Leer nota
Si nota < 0 O nota > 10 Entonces
Escribir "Valor fuera de rango"
FinSi
Hasta Que nota >= 0 Y nota <= 10
Escribir "Nota aceptada: ", nota
FinAlgoritmo
Input validation is the perfect job for Repetir: you must ask at least once, and you keep asking until the answer is valid. Menus that run "until the user chooses Exit" are another classic.
PSeInt also accepts the variant Mientras Que condición at the end of a Repetir, which repeats while the condition is true — choose whichever reads more naturally, but be consistent.
Which loop should I use?
| Situation | Best loop | Why |
|---|---|---|
| Process N items, print a table, walk an array | Para | The number of passes is known |
| Read data until a sentinel value | Mientras | May need zero passes |
| Repeat a calculation until it converges | Mientras | Unknown number of passes |
| Validate user input, show a menu | Repetir | Must run at least once |
Any loop can be rewritten using the others, but using the natural one makes your intention obvious to whoever reads the code — including you, two weeks later.
Essential loop patterns
Counter
A variable that increases by one each time something happens. Initialise it to 0 before the loop.
Accumulator
A variable that adds up values. Initialise sums to 0 and products to 1.
Algoritmo ContadorYAcumulador
Definir i, n, valor, positivos Como Entero
Definir suma Como Real
positivos <- 0
suma <- 0
Escribir "¿Cuántos números va a ingresar?"
Leer n
Para i <- 1 Hasta n Hacer
Escribir "Número ", i, ":"
Leer valor
suma <- suma + valor
Si valor > 0 Entonces
positivos <- positivos + 1
FinSi
FinPara
Escribir "Suma: ", suma
Escribir "Positivos: ", positivos
FinAlgoritmo
Maximum and minimum
Assume the first value is both the maximum and the minimum, then correct the assumption as new values arrive. Starting from the first value (not from 0) makes the algorithm work for negative numbers too.
Algoritmo MaximoYMinimo
Definir i, n Como Entero
Definir x, mayor, menor Como Real
Escribir "Cantidad de valores:"
Leer n
Escribir "Valor 1:"
Leer x
mayor <- x
menor <- x
Para i <- 2 Hasta n Hacer
Escribir "Valor ", i, ":"
Leer x
Si x > mayor Entonces
mayor <- x
FinSi
Si x < menor Entonces
menor <- x
FinSi
FinPara
Escribir "Mayor: ", mayor, " Menor: ", menor
FinAlgoritmo
Flag (bandera)
A Logico variable that records whether something happened, often used to stop a search early:
Algoritmo EsPrimo
Definir n, d Como Entero
Definir primo Como Logico
Escribir "Número:"
Leer n
primo <- n > 1
d <- 2
Mientras primo Y d * d <= n Hacer
Si n MOD d = 0 Entonces
primo <- Falso
FinSi
d <- d + 1
FinMientras
Si primo Entonces
Escribir n, " es primo"
SiNo
Escribir n, " no es primo"
FinSi
FinAlgoritmo
The loop stops as soon as a divisor is found, and it only tests divisors up to the square root (d * d <= n) — a simple optimisation that makes it much faster for big numbers.
Nested loops
A loop inside another loop runs completely for each pass of the outer one. Nested loops are how you draw grids, walk matrices and compare every pair of items.
Algoritmo Triangulo
Definir fila, col, n Como Entero
n <- 5
Para fila <- 1 Hasta n Hacer
Para col <- 1 Hasta fila Hacer
Escribir Sin Saltar "*"
FinPara
Escribir ""
FinPara
FinAlgoritmo
The inner loop's end value depends on the outer variable, producing a triangle of stars. Escribir Sin Saltar keeps the stars on the same line, and the empty Escribir "" moves to the next line after each row. Total inner passes: 1 + 2 + 3 + 4 + 5 = 15.
Infinite loops: causes and cures
An infinite loop never ends because its condition never changes. Typical causes:
- Forgetting the update. A
Mientras i <= 10whose body never changesi. - Updating in the wrong direction.
i <- i - 1when the condition waits forito grow. - Reversed condition in Repetir. Writing
Hasta Que nota < 0 O nota > 10keeps asking only while the input is valid — exactly backwards. - Exact comparison with decimals.
Mientras x <> 1withx <- x + 0.1may skip past 1 because of rounding. Use<instead of<>.
In the desktop PSeInt you can stop a runaway program from the toolbar. Our online editor has a Stop button and also stops automatically after two million instructions, telling you on which line the loop was running.
Tracing a loop by hand
Teachers often ask you to "trace" (or "desk-check") a loop: run it on paper and record the value of each variable after every pass. It's the best way to predict what a loop does without a computer. Take this fragment:
suma <- 0
Para i <- 1 Hasta 4 Hacer
suma <- suma + i * i
FinPara
| Pass | i | i * i | suma after the pass |
|---|---|---|---|
| 1 | 1 | 1 | 1 |
| 2 | 2 | 4 | 5 |
| 3 | 3 | 9 | 14 |
| 4 | 4 | 16 | 30 |
The final value is 30. Now compare your table with the Variables tab of the online editor while stepping through the same code: if they match, you truly understand the loop.
Loops and performance
Beginners rarely need to worry about speed, but it's worth knowing that nested loops multiply the work: two nested loops of 1,000 passes each execute the inner body one million times. When a program feels slow, look for work that can be done once before the loop instead of on every pass, and stop searches as soon as you find what you need.
Solved exercise: guess the number
This small game combines a random number, a Repetir loop, a counter and nested conditions:
Algoritmo Adivinar
Definir secreto, intento, intentos Como Entero
secreto <- ALEATORIO(1, 100)
intentos <- 0
Escribir "Adivine el número entre 1 y 100"
Repetir
Leer intento
intentos <- intentos + 1
Si intento < secreto Entonces
Escribir "Más alto"
SiNo
Si intento > secreto Entonces
Escribir "Más bajo"
FinSi
FinSi
Hasta Que intento = secreto
Escribir "¡Correcto! Lo logró en ", intentos, " intentos"
FinAlgoritmo
With a clever strategy (always guess the middle of the remaining range) you never need more than 7 attempts — a nice introduction to binary search.
Practice exercises
- Print the even numbers from 2 to 50 using
Con Paso 2. - Compute the factorial of N with a
Paraloop (accumulator initialised to 1). - Read numbers until 0 is entered and print how many were negative.
- Show a menu (1-Sumar, 2-Restar, 3-Salir) with
Repetiruntil the user picks 3. - Print the multiplication tables from 1 to 10 using nested loops.
Next, learn to store many values at once in the arrays and matrices guide — loops and arrays are made for each other. You can also browse the solved examples in the Loops category.
Frequently asked questions
What is the difference between Mientras and Repetir in PSeInt?
Mientras checks the condition first and repeats while it is true (it may run zero times). Repetir runs the body first and repeats until the condition is true (it always runs at least once).
Can a Para loop count backwards?
Yes: use a negative step, for example Para i <- 10 Hasta 1 Con Paso -1 Hacer.
What value does the variable have after a Para loop?
Don't rely on it. Treat the control variable as valid only inside the loop; if you need a value afterwards, store it in another variable.
Does PSeInt have break or continue?
No. To leave a loop early, use a Mientras with a flag in its condition, as in the prime-number example.