+ 12
[SOLVED]i have a small issue with this loop.please, why after iterate it ,the result of a[i] is always equals to 2 but not 3 ?
int a[] ={3,2,1}; for (int i= 1; i < 3; i++){ a[0] *= a[i]; // why here is 3*2 but not 3*3. System.out.println(a[0]); } //output: 6 for solving it I have started to count at 2 because int i = 1, then after the condition i < 3 I thought that a[i] must be equals to 2+1 (after iteration ) but no, it's only 2 which is used for a[i],why?? (here is my doubt) sorry for my English😊 all contributions are welcome .thanks in advance😊.
9 Antworten
+ 15
👍got Manual ,my mistake was to think that loop starts at 1 and makes addition of a[1] and a[2] (2+1 when is less than 3) before to multiplies the result of addition by the value of a[0] .
finally i can understand how this loop runs! now it's ok! thank you!
+ 11
sorry D⚽⚽⚽⚽7⃣7⃣7⃣ I forgot to write System.out.println(a[0]);
+ 7
Hans Larry Mba Bekale
because the loop multiplies only the values of a[1] and a[2]
loop starts at 1 stops when i is not less than 3
i = 1
a[0] = a[0] * a[1]
a[0] = 3*2
i = 2
a[0] = a[0] * a[2]
a[0] = 6*1
end of loop
+ 4
First I think you should declare an other variable to store the result for example int res. The loop should be changed I=0; I <=2, then res *= a[i]
I think that should give you the right result.Your array index starts always at 0 and ends at length - 1.
+ 4
I think it's better to store the result in a variable, because otherwise you are making changes in the array elements. Also it's better to loop through all elements from index 0 to array.length, because then you can be sure that you don't skip an element of the array.
+ 4
you should have put = in for loop..
for( int i =1; i <= 3; i++)
another way is to take 4 in test condition..
for(int i=1; i < 4; i++)
+ 2
It's because within your for loop I will never be 3 based on the condition you gave it.
+ 1
Loop works the way You wrote it. So, in first iteration you have i=1 which gives a[0]=3*2 which is 6. In second iteration it is i=2 which gives a[0]=6*1 which is 6.
When loop ends your array is {6,2,1}
0
Your variables are ok but for some reason the system output is alittle messed up