Populating an array with user input of size not working in C# -


i want let user define size of array , of numbers inside it, had in mind:

int []arr={0}; console.writeline("please enter size of array:"); size = console.read();  for(int i=0; i<size; i++) {     console.writeline("please enter next number in array, it's position is: " + i);     arr[i] = console.read(); } 

when try run gives me 'index out of range' error. if point doing wrong appreciate it.

edit: after answer changed code little bit , looks this:

console.writeline("please enter size of array:"); input = console.readline(); size = int.parse(input); int[] arr = new int[size];  for(int i=0; i<size; i++) {     string b;     console.writeline("please enter next number in array, it's position is: " + i);     b = console.readline();     arr[i] = int.parse(b);  } 

so array can bigger , numbers inside, again help!

you need initialize array after getting input user:

console.writeline("please enter size of array:"); int size = int.parse(console.readline()); //you need parse input int[] arr = new int[size];  for(int i=0; < arr.length; i++) {     console.writeline("please enter next number in array, it's position is: " + i);     arr[i] = int.parse(console.readline()); //parsing "int" } 

note: should not use console.read() returns ascii of character szabolcs dézsi mentioned in comments. should use console.readline() instead.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -