Objective
Create a program to allow the user to enter an unlimited amount of numbers. Also, they can enter the following commands:
"sum", to display the sum of all the numbers entered so far.
"view", to display all the numbers entered.
"end", to quit the program.
This is an execution sample:
Number or command? 5
Number or command? 3
Number or command? view
Entered numbers:
5
3
Number or command? 6
Number or command? sum
Sum = 14
Number or command? -7
Number or command? end
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces for basic functionality
using System;
using System.Collections.Generic; // For using List
class Program
{
static void Main(string[] args)
{
// List to store the numbers entered by the user
List numbers = new List();
// Start an infinite loop to keep asking the user for input
while (true)
{
// Prompt user to enter a number or command
Console.Write("Number or command? ");
string input = Console.ReadLine();
// Check if the input is a command
if (input == "sum")
{
// Calculate the sum of all entered numbers
int sum = 0;
foreach (int number in numbers)
{
sum += number;
}
// Display the sum
Console.WriteLine("Sum = " + sum);
}
else if (input == "view")
{
// Display all the numbers entered so far
Console.WriteLine("Entered numbers:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
else if (input == "end")
{
// Exit the program
break;
}
else
{
// Try to convert the input to a number
if (int.TryParse(input, out int number))
{
// Add the number to the list if it is valid
numbers.Add(number);
}
else
{
// Inform the user if the input is invalid
Console.WriteLine("Invalid input, please enter a number or a valid command.");
}
}
}
Console.WriteLine("Program has ended.");
}
}