Computer Applications
Give the output of the following program segment:
int x[]={2,45,7,67,12,3};
int i, t=0;
for(i=0, t=5;i<3;i++,t--)
{
System.out.println(x[i]+x[t]);
}
Answer
Output
5
57
74
Explanation
1. Array x = [2, 45, 7, 67, 12, 3].
2. Initial values: i = 0, t = 5.
3. Loop condition: i < 3 (loop runs for i = 0, 1, 2)
Iteration 1:
i = 0, t = 5x[0] + x[5] = 2 + 3 = 5- Print:
5 - After iteration:
i = 1, t = 4
Iteration 2:
i = 1, t = 4x[1] + x[4] = 45 + 12 = 57- Print:
57 - After iteration:
i = 2, t = 3
Iteration 3:
i = 2, t = 3x[2] + x[3] = 7 + 67 = 74- Print:
74 - After iteration:
i = 3, t = 2
Loop ends because i is now 3 (not less than 3).
4. So the output is:
5
57
74
Related Questions
Mention the output of this code snippet:
int lives = 5; System.out.println(lives--); System.out.println(lives);Convert the following for loop segment to an exit-controlled loop.
for(k = 10;k >= -1;k--) System.out.println(k*2); System.out.println(k*4);Write Java statements for the following:
(a) Initialise the array with the three favourite subjects.
(b) Declare an array to store the marks in 3 subjects of 40 students.A Student executes the given program segment and it results in 1.0, irrespective of the value of n. State the type of the error, write the correct statement:
void solve(int n) { double power=Math.pow(n, 2/3); System.out.println(power); }