Sum Until Zero
Adds up the numbers you type until you enter a 0.
- Level
- Beginner
- Topic:
- Loops
- Concepts:
- Input & output
- Mientras
- Si
Open in Codoritmo
Run, change and debug this example in your browser.
What you'll learn
A Mientras loop stops on a sentinel value, here the 0. An accumulator (suma) and a counter (cantidad) give you the average.
Code
Algoritmo SumaHastaCero Definir numero, suma Como Real Definir cantidad Como Entero suma <- 0 cantidad <- 0 Escribir "Escribe números para sumar. Escribe 0 para terminar." Leer numero Mientras numero <> 0 Hacer suma <- suma + numero cantidad <- cantidad + 1 Escribir "Siguiente número (0 para terminar):" Leer numero FinMientras Si cantidad > 0 Entonces Escribir "Sumaste ", cantidad, " números." Escribir "Total: ", suma Escribir "Promedio: ", suma / cantidad SiNo Escribir "No escribiste ningún número." 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.
Escribe números para sumar. Escribe 0 para terminar.User answer: 12Siguiente número (0 para terminar):User answer: 7.5Siguiente número (0 para terminar):User answer: 30Siguiente número (0 para terminar):User answer: 0Sumaste 3 números.Total: 49.5Promedio: 16.5
Challenge
Also show the largest number that was typed.
Show hint
Store the first number in a mayor variable and update it with a Si inside the loop.
Related examples
Guess the Number
Guess a secret number from 1 to 100 in seven tries.
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.
Intermediate