elliot
elliot

Reputation: 39

How to put the user input in a array and go through the array in C#

Im making a code that gets the user input and put then in descending order, but i need help in this part, to put the user input into a array, the much input the user make, only stopping when '-1' is typed. Here is the code:

 int []vet = new int[]{};

for(int i = 0; i != -1;i++)
{
    Console.WriteLine("digite os valores");
    int input = int.Parse(Console.ReadLine());
    vet[i] = input;

}

This code generates this error: "Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array."

Upvotes: 1

Views: 119

Answers (2)

Jonathan Barraone
Jonathan Barraone

Reputation: 487

Try something like this:

List<int> vet = new List<int>();
int Response = 0;

Console.WriteLine("digite os valores");
Response = int.Parse(Console.ReadLine());
vet.Add(Response);

while (Response != -1)
{
     Console.WriteLine("digite os valores");
     Response = int.Parse(Console.ReadLine());
     vet.Add(Response);
}

Upvotes: 2

devi
devi

Reputation: 43

I noticed 2 major problems with your code.

A. you used an array for a dynamic sized list. B. you used a for loop for an unknown amount of iterations.

The solution for problem A is, use a List<int> from the namespace System.Collections.Generic (important to import that)

For problem B you should use a while loop and check when an input variable is equals to -1, then close the loop.

Upvotes: 2

Related Questions