Grupo
Conceptos básicos control de flujo en C#
Objectivo
El objetivo de este ejercicio es escribir un programa en C# que solicite al usuario una cantidad indeterminada de números (hasta que se introduzca 0) y muestre su suma.
Escriba un programa en C# que solicite al usuario una cantidad indeterminada de números (hasta que se introduzca 0) y muestre su suma, de la siguiente manera:
Número: 5
Total = 5
Número: 10
Total = 15
Número: -2
Total = 13
Número: 0
Terminado.
Ejemplo de ejercicio en C#
Mostrar código C#
// First and Last Name: John Doe
using System;
namespace SumUserInput
{
class Program
{
// Main method to execute the program
static void Main(string[] args)
{
// Initialize a variable to store the total sum
int total = 0;
int number;
// Start an infinite loop that will break when 0 is entered
while (true)
{
// Ask the user to enter a number
Console.Write("Number? ");
number = int.Parse(Console.ReadLine()); // Read and parse the user's input
// If the entered number is 0, break the loop and finish
if (number == 0)
{
break;
}
// Add the entered number to the total sum
total += number;
// Display the running total
Console.WriteLine("Total = " + total);
}
// Once the loop is finished (0 entered), display "Finished"
Console.WriteLine("Finished");
}
}
}
Output
Number? 5
Total = 5
Number? 10
Total = 15
Number? -2
Total = 13
Number? 0
Finished
Código de ejemplo copiado
Comparte este ejercicio de C#