What will be the output of the below program?public class Demo { public static void main(String[] args) { int sum = 0; for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1) { sum += i; } System.out.println(sum); }}
Question
What will be the output of the below program?public class Demo { public static void main(String[] args) { int sum = 0; for (int i = 0, j = 0; i < 5 & j < 5; ++i, j = i + 1) { sum += i; } System.out.println(sum); }}
Solution
The output of the program will be 10.
Here's the step-by-step explanation:
-
The program starts with the initialization of the variable
sumto 0. -
Then, a for loop is started with two variables
iandj, both initialized to 0. -
The condition for the loop to continue is
i < 5 & j < 5. The&operator is a bitwise AND, which means both conditions have to be true for the loop to continue. -
Inside the loop,
sumis incremented byi. -
After the loop body,
iis incremented by 1 (++i), andjis set toi + 1. -
The loop continues until
i < 5 & j < 5is no longer true. This happens whenibecomes 4 andjbecomes 5. -
The values added to
sumduring each iteration of the loop are 0, 1, 2, 3, and 4. -
Adding these numbers together gives the final value of
sum, which is 10. -
This value is then printed to the console.
Similar Questions
What will be the output of the following program?public class Test{ public static void main(String args[]){ int i = 0, j = 5 ; for( ; (i < 3) && (j++ < 10) ; i++ ){ System.out.print(" " + i + " " + j ); } System.out.print(" " + i + " " + j ); }}0 6 1 7 2 8 3 80 6 1 7 2 8 3 90 6 1 5 2 5 3 5Compilation Erro
t answerWhat will be the output of the following Java program?class control_statements { public static void main(String args[]) { int sum = 0; for (int u = 5, v = 5; u < 10 & v < 10; ++u, v = u + 1) sum += u; System.out.println(sum); } }
Select the correct answerWhat will be the output of the following Java code?class array_output { public static void main(String args[]) { int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}}; int sum = 0; for (int i = 1; i < 3; ++i) for (int j = 1; j < 3 ; ++j) sum = sum + array_variable[i][j]; System.out.print(sum / 6); } }Options8413
the correct answerWhat is the output of the following code snippet?for (int i = 0; i < 5; i++) { System.out.print(i + " ");}
What is the output of the following code :class MyClass {public static void main(String[] args) {int i=1,j=1;for (;i<3;i++){for(;j<4;j++);j++;System.out.print(i + j+" ");}}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.