Predict the output of the given snippet.
int a[]={1,2,3,4,5};
int i;
a[1]=a[3];
a[2]=a[1];
for(i=0;i<2;i++)
System.out.println(a[i]+a[4-i]);
Predict the output of the given snippet.
int a[]={1,2,3,4,5};
int i;
a[1]=a[3];
a[2]=a[1];
for(i=0;i<2;i++)
System.out.println(a[i]+a[4-i]);
e) Predict the output of the given pr
Answers
Answered by
6
Corrected Code:
int a[] = {1, 2, 3, 4, 5};
int i;
a[1]=a[3];
a[2]=a[1];
for(i = 0; i < 2; i++)
System.out.println(a[i] + a[4-i]);
The Output:
6
8
The Calculation:
Consider the Array:
Element at index 1 now stores the value present at index 3. Array becomes:
Element at index 2 now stores value present at index 1. Array becomes:
Now, consider the for loop:
When i = 0,
> a[i] + a[4 - i] = a[0] + a[4 - 0]
= a[0] + a[4]
= 1 + 5
= 6
> 6 is printed.
When i = 1,
> a[i] + a[4 - i] = a[1] + a[4 - 1]
= a[1] + a[3]
= 4 + 4
= 8
> 8 is printed.
So, the numbers 6 and 8 are displayed on the screen!
Similar questions
English,
29 days ago
English,
29 days ago
Hindi,
2 months ago
Environmental Sciences,
9 months ago
Social Sciences,
9 months ago