Computer Science, asked by Ghosha9933, 2 months ago

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 anindyaadhikari13
6

Corrected Co‎de:

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:

\boxed{\begin{array}{c|c}\tt \underline{Element}:&amp;\tt \underline{Index}:\\ \tt1&amp;\tt0\\ \tt2&amp;\tt1\\ \tt3&amp;\tt2\\ \tt4&amp;\tt3\\ \tt5&amp;\tt4\end{array}}

Element at index 1 now stores the value present at index 3. Array becomes:

\boxed{\begin{array}{c|c}\tt \underline{Element}:&amp;\tt \underline{Index}:\\ \tt1&amp;\tt0\\ \tt4&amp;\tt1\\ \tt3&amp;\tt2\\ \tt4&amp;\tt3\\ \tt5&amp;\tt4\end{array}}

Element at index 2 now stores value present at index 1. Array becomes:

\boxed{\begin{array}{c|c}\tt \underline{Element}:&amp;\tt \underline{Index}:\\ \tt1&amp;\tt0\\ \tt4&amp;\tt1\\ \tt4&amp;\tt2\\ \tt4&amp;\tt3\\ \tt5&amp;\tt4\end{array}}

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