Exercise
Many Numbers And Sum
Objective
Write a C# program which asks the user for several numbers (until he enters "end" and displays their sum). When the execution is going to end, it must display all the numbers entered, and the sum again, as follows:
Enter a number: 5
Sum = 5
Enter a number: 3
Sum = 8
Enter a number: end
The numbers are: 5 3
The sum is: 8
Write Your C# Exercise
C# Exercise Example
using System; // Import the System namespace for basic functionality
class Program // Define the main class
{
static void Main() // The entry point of the program
{
double sum = 0; // Variable to store the sum of the numbers
string input; // Variable to store user input
string numbersEntered = ""; // String to store the entered numbers
// Prompt user for numbers until they enter "end"
Console.WriteLine("Enter numbers (type 'end' to stop):");
// Continue looping until user enters "end"
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine(); // Read user input
if (input.ToLower() == "end") // Check if input is "end"
break; // Exit the loop if "end" is entered
// Try to convert the input to a double and add it to the sum
if (double.TryParse(input, out double number))
{
sum += number; // Add the number to the sum
numbersEntered += number + " "; // Append the number to the list of entered numbers
Console.WriteLine($"Sum = {sum}"); // Display the current sum
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
// Display the entered numbers and the total sum once "end" is entered
Console.WriteLine($"The numbers are: {numbersEntered.Trim()}");
Console.WriteLine($"The sum is: {sum}");
}
}