1

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."

4
  • I recommend you take a step back and learn how to debug your code at run time. Here are a few of the many resources available: Navigate through code with the Visual Studio debugger, Learn to debug C# code using Visual Studio, and Debugging C# Code in Visual Studio | Mosh. Commented Nov 22, 2022 at 20:15
  • 1
    Use List<int> instead to store user's input so that you won't have to worry about the index anymore. Plus, you declare an array of 0 length that is why you get this error. And your FOR loop is an infinite one cause i != -1 will always be true and you'll never reach -1. You should avoid doing that. Commented Nov 22, 2022 at 20:18
  • If you need a container without fixed size, then use one. Arrays are fixed size. Also, i is going to be always != -1 in your code. So you got yourself an infinite loop, there. But of course, trying to access an array index that out of bounds is going to throw. That means: fix those two things: 1. Use a list instead of an array 2. Fix your loop-ending-condition. Commented Nov 22, 2022 at 20:35
  • Thanks guys, it worked, i improved my code, changed the array to a list and the loop Commented Nov 22, 2022 at 22:04

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.