Guess the Number
Guess a secret number from 1 to 100 in seven tries.
- Level
- Intermediate
- Topic:
- Loops
- Concepts:
- Input & output
- Mientras
- Si
- Randomness
- Logic
Run, change and debug this example in your browser.
What you'll learn
Aleatorio picks the secret number and Mientras keeps going while two conditions joined with Y and NO hold. Abs measures how close you are, and Escribir Sin Saltar stays on the same line.
Code
Algoritmo AdivinaNumero Definir secreto, intento, intentos Como Entero Definir acerto Como Logico secreto <- Aleatorio(1, 100) intentos <- 0 acerto <- Falso Escribir "Pensé un número del 1 al 100. Tienes 7 intentos." Mientras (NO acerto) Y intentos < 7 Hacer intentos <- intentos + 1 Escribir "Intento ", intentos, ":" Leer intento Si intento = secreto Entonces acerto <- Verdadero SiNo Si intento < secreto Entonces Escribir Sin Saltar "Más alto" SiNo Escribir Sin Saltar "Más bajo" FinSi // Abs da la distancia sin importar el signo Si Abs(intento - secreto) <= 5 Entonces Escribir ", ¡estás muy cerca!" SiNo Escribir "..." FinSi FinSi FinMientras Si acerto Entonces Escribir "¡Correcto! Lo lograste en ", intentos, " intentos." SiNo Escribir "Se acabaron los intentos. Era el ", secreto, "." FinSiFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
Pensé un número del 1 al 100. Tienes 7 intentos.Intento 1:User answer: 50Más bajo...Intento 2:User answer: 25¡Correcto! Lo lograste en 2 intentos.
Challenge
At the end, show a special message if you won in three tries or fewer.
Show hint
Inside the Si acerto branch, add another Si that checks intentos <= 3.
Related examples
Bubble 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.
IntermediateShell Sort
Insertion sort between far-apart elements, with a gap that shrinks every pass.
Advanced