Last active
April 29, 2025 14:39
-
-
Save Strelok78/70abc227b5787820abc796afd46c52ef to your computer and use it in GitHub Desktop.
Get sum of dinamicaly changed array without LINQ and array.resize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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