New course! Every coder should learn Generative AI!
Try a free lesson+ 2
Can anyone explain why is the output 3?
int [] a = {4,2,3}; for (int i = 0; i < 3; i++) { a[0] = a[i]; } System.out.print(a[0]); Output: 3
5 Answers
+ 1
because you are just printing only one list value (a[0] which is 3). If you want to print all values in list (i.e 3,2,3 not 4,2,3 because you looped it with 'for' right?) Use print (a). just a. Don't use index. Index are used for specific value in list.
+ 3
// If your purpose is to iterate (loop through each values of) the array and print each item, you need to do:
int [] a = {4,2,3};
for (int i = 0; i < 3; i++) {
System.out.print(a[i]);
}
// Output (digit by digit, even if you don't see them displayed one by one as there's no delay between each print):
423
+ 2
Because you are assign a[0] (index position 0 of 'a' list) to current a[i value].So,
1st loop: a[0] = 4
2nd loop: a[0] = 2
3rd loop: a[0] = 3
Then condition become false, so loop end.
Therefore, result : a[0] = 3
+ 1
The print is out of for loop. it is only printing value at index 0 which became 3 after the loop
0
Why is the output just 3. Why is not it 423?