Skip to content

Instantly share code, notes, and snippets.

@Strelok78
Last active April 29, 2025 14:39
Show Gist options
  • Save Strelok78/70abc227b5787820abc796afd46c52ef to your computer and use it in GitHub Desktop.
Save Strelok78/70abc227b5787820abc796afd46c52ef to your computer and use it in GitHub Desktop.
Get sum of dinamicaly changed array without LINQ and array.resize
using System;
namespace iJuniorPractice
{
class Program
{
static void Main(string[] args)
{
const string SumCommand = "sum";
const string ExitCommand = "exit";
int sum = 0;
int arrayLength = 0;
int[] numbers = new int[arrayLength];
string input;
bool isWork = true;
while (isWork)
{
Console.Write($"Enter a number to add to the array, or type {SumCommand} to calculate the sum, or {ExitCommand} to quit: ");
input = Console.ReadLine();
switch (input)
{
case SumCommand:
foreach (var number in numbers)
{
sum += number;
}
Console.WriteLine($"Sum of the array elements: {sum}");
break;
case ExitCommand:
Console.WriteLine("Exiting the program.");
isWork = false;
break;
default:
int enteredNumber;
while (int.TryParse(input, out enteredNumber) == false)
{
Console.WriteLine("Invalid input. Please enter an integer.");
input = Console.ReadLine();
}
arrayLength++;
int[] temporary = new int[arrayLength];
for (int i = 0; i < numbers.Length; i++)
{
temporary[i] = numbers[i];
}
temporary[arrayLength - 1] = enteredNumber;
numbers = temporary;
Console.WriteLine("Number added to the array.");
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment