T
T
TargetT_PoweR2020-03-26 19:52:39
Arrays
TargetT_PoweR, 2020-03-26 19:52:39

How to fill an array with user-entered numbers?

Hello.
I faced a difficult task for myself:

The user enters numbers, and the program remembers them.
As soon as the user enters the sum command, the program will display the sum of all the entered numbers.
The program should only exit if the user issues the exit command.
The program should work based on array expansion.
Attention, you cannot use List and Array.Resize

My solution looked like this:

int sum = 0;
int[] firstMas = new int[0];
while (true)
{
string userInput = Console.ReadLine();
if (userInput == "exit")
{
break;
}
else if (userInput == "sum")
{
Console.WriteLine("The sum of the entered numbers is " + sum);
break;
}
int[] secondMas = new int[firstMas.Length + 1];
int number = Convert.ToInt32(userInput);
secondMas[secondMas.Length - 1] = number;
firstMas = secondMas;
sum += number;
Console.WriteLine("Array length: " + firstMas.Length);

The decision was not made, the question is - what are my mistakes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2020-03-26
@TargeT_PoweR

Your version corrected
int[] firstMas = new int[0];
            while (true) {
                string userInput = Console.ReadLine();
                if (userInput == "exit")
                {
                    break;
                }
                else if (userInput == "sum")
                {
                    int sum = 0;
                    for (int i = 0; i < firstMas.Length; i++)
                        sum += firstMas[i];
                        Console.WriteLine("Сумма введённых чисел равна " + sum);
                }
                else
                {
                    int[] secondMas = new int[firstMas.Length + 1];
                    int number = Convert.ToInt32(userInput);
                    secondMas[secondMas.Length - 1] = number;
                    for (int i = 0; i < firstMas.Length; i++)
                        secondMas[i] = firstMas[i];
                    firstMas = secondMas;
                    Console.WriteLine("Длинна массива: " + firstMas.Length);
                }

New option
int[] arr = new int[0];
            while (true){
                string s = Console.ReadLine();
                switch (s){
                    case "exit":
                        return;
                    case "sum":
                        Console.WriteLine(String.Format("Сумма введённых чисел = '{0}'", arr.Sum()));
                        break;
                    default:
                        int result;
                        if (int.TryParse(s, out result))
                            arr = arr.Concat(new int[] { result }).ToArray();
                        break;

                }
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question