Exercise
Sum numbers
Objetive
Write a C# program to ask the user for an undetermined amount of numbers (until 0 is entered) and display their sum, as follows:
Number? 5
Total = 5
Number? 10
Total = 15
Number? -2
Total = 13
Number? 0
Finished"
Example Code
using System; // Importing the System namespace to use Console functionalities
class Program
{
// Main method where the program execution begins
static void Main()
{
int number; // Declaring a variable to store the number entered by the user
int total = 0; // Declaring and initializing the total variable to 0
// Using a while loop to repeatedly ask for numbers until 0 is entered
while (true) // The loop will continue indefinitely until 0 is entered
{
// Asking the user to enter a number
Console.Write("Number? ");
number = Convert.ToInt32(Console.ReadLine()); // Converting the input to an integer
// Breaking out of the loop if the number entered is 0
if (number == 0) // If the entered number is 0, the program will stop
{
break; // Exiting the loop
}
// Adding the entered number to the total
total += number; // Accumulating the sum of the numbers
Console.WriteLine("Total = " + total); // Displaying the current total
}
// Displaying the finished message once the loop ends
Console.WriteLine("Finished"); // Informing the user that the program has finished
}
}