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()); }

10th Sep 2021, 4:43 PM
ASENCIO ORTIZ SAEZ
8 Respostas
+ 2
Just use the for-loop instead of the foreach-loop to populate the array
11th Sep 2021, 7:16 AM
Lisa
Lisa - avatar
+ 1
In the foreach-version, "item" is the actual element and not an index as in for-version
10th Sep 2021, 5:07 PM
Lisa
Lisa - avatar
+ 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.
10th Sep 2021, 5:34 PM
Lisa
Lisa - avatar
+ 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.
10th Sep 2021, 5:45 PM
Coding Cat
Coding Cat - avatar
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.
10th Sep 2021, 5:18 PM
ASENCIO ORTIZ SAEZ
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? :(
10th Sep 2021, 11:27 PM
ASENCIO ORTIZ SAEZ
0
So in this is case its not the best way using the foreach loop. Great. Thx Lisa again ;)
11th Sep 2021, 8:53 AM
ASENCIO ORTIZ SAEZ