0
Hi guys! Trying to fill an array asking the user for numbers. It's not working with foreach.Only prints position [2]. Ideas? Thx
int[ ] array = new int [ 2 ]; //for loop Console.WriteLine("Enter number:"); For(int i=0;i<array.Length;i++); { array[i]=int.Parse(Console.ReadLine()); } Console.WriteLine("Enter a number:"); foreach(int item in array) { array[item]=int.Parse(Consola.ReadLine()); }
8 ответов
+ 2
Just use the for-loop instead of the foreach-loop to populate the array
+ 1
In the foreach-version, "item" is the actual element and not an index as in for-version
+ 1
Output "item" in the foreach loop – it is always 0 as all elements of the array are 0. Therefore only ever the first element of the array gets the input.
+ 1
Yes, Lisa is right.
At start is
array = [0, 0]
After first input
array = [first Input, 0]
After second input
array = [second input, 0]
Put some print statements into the code, to show what's going on.
0
Thx Lisa for your reply.
Yeah,I know. The thing is that I dont know why the number in first position [0] is not added and only the number after the first position is added.
0
I see.
Exactly. If the first num entered is 50 and the second one 22, It prints 22 and 0.
So how can I Sort It out?
What should I change in my Code to get as output 50 and 22? :(
0
So in this is case its not the best way using the foreach loop. Great.
Thx Lisa again ;)