Skip to content

Instantly share code, notes, and snippets.

@Strelok78
Last active April 23, 2025 13:43
Show Gist options
  • Select an option

  • Save Strelok78/09818c87526caef617d60555317fcbe0 to your computer and use it in GitHub Desktop.

Select an option

Save Strelok78/09818c87526caef617d60555317fcbe0 to your computer and use it in GitHub Desktop.
Get sum of entered values using List collection
using System.Collections;
using System.Diagnostics;
namespace iJuniorPractice;
class Program
{
static void Main(string[] args)
{
const string SumCommand = "Sum";
const string ExitCommand = "Exit";
List<int> numbers = new List<int>();
string userInput;
bool isWork = true;
while (isWork)
{
Console.WriteLine($"Eneter values " +
$"or \"{SumCommand}\" to get sum of the entered values " +
$"or \"{ExitCommand}\" to exit program");
userInput = Console.ReadLine();
switch (userInput)
{
case SumCommand:
Console.WriteLine(CalculateSum(numbers));
break;
case ExitCommand:
Console.WriteLine("Goodbye!");
isWork = false;
break;
default:
numbers.Add(ReadInt(userInput));
break;
}
Console.WriteLine("Enter any key to continue...");
Console.ReadKey();
Console.Clear();
}
}
static int CalculateSum(List<int> numbers)
{
int sum = 0;
foreach (var number in numbers)
{
sum += number;
}
return sum;
}
static int ReadInt(string input)
{
int number;
while (int.TryParse(input, out number) == false)
{
Console.WriteLine("Incorrect value!");
Console.Write("Enter value: ");
input = Console.ReadLine();
}
return number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment