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+" ");}}
Question
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+" ");}}
Solution
To determine the output of the given code, let's analyze it step by step:
-
The code starts with the declaration of a class named "MyClass".
-
Inside the class, there is a main method, which is the entry point of the program.
-
Two integer variables, "i" and "j", are declared and initialized to 1.
-
The outer for loop starts with the condition "i<3". This loop will execute twice.
-
Inside the outer loop, there is an inner for loop with the condition "j<4". However, this inner loop does not have any statements inside its body.
-
After the inner loop, there is a statement "j++", which increments the value of "j" by 1.
-
Then, there is another statement "j++", which increments the value of "j" by 1 again.
-
Finally, there is a statement "System.out.print(i + j + " ");", which prints the sum of "i" and "j" followed by a space.
Now, let's go through the iterations of the loops:
-
In the first iteration of the outer loop, "i" is 1. The inner loop does not have any statements, so "j" remains 1. The statement "System.out.print(i + j + " ");" prints "1 + 1 = 2".
-
In the second iteration of the outer loop, "i" is 2. Again, the inner loop does not have any statements, so "j" remains 2. The statement "System.out.print(i + j + " ");" prints "2 + 2 = 4".
Therefore, the output of the given code will be "2 4".
Similar Questions
What is output of the following code:public class Test{ public static void main(String[] args){ int[] x = {120, 200, 016 }; for(int i = 0; i < x.length; i++) System.out.print(x[i] + " "); }
e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}
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
What is the output of the following?class GFG{ public static void main (String[] args) { int[] arr = new int[2]; arr[0] = 10; arr[1] = 20; for (int i = 0; i <= arr.length; i++) System.out.println(arr[i]); }}
Determine output:public class Test{ public static void main(String args[]){ int i, j; for(i=1, j=0;i<10;i++) j += i; System.out.println(i); }}1011920
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.