Find the output of the following code.class Output { public static void main(String args[]) { int arr[] = {11, 21, 31, 41, 51}; for ( int i = 1; i < arr.length - 2; ++i) System.out.println(arr[i] + " "); } }*11 21 31 4111 21 3121 3131 41 51
Question
Find the output of the following code.class Output { public static void main(String args[]) { int arr[] = {11, 21, 31, 41, 51}; for ( int i = 1; i < arr.length - 2; ++i) System.out.println(arr[i] + " "); } }*11 21 31 4111 21 3121 3131 41 51
Solution
The code is written in Java. It declares an array of integers and then prints out the elements of the array from the second element to the second last element. Here's a step-by-step explanation:
-
The array
arris declared and initialized with the values{11, 21, 31, 41, 51}. -
A for loop is set up to iterate over the array. The loop variable
iis initialized to 1, which is the second element in the array (since array indices start at 0 in Java). -
The loop continues as long as
iis less thanarr.length - 2. Thelengthproperty of an array in Java gives the number of elements in the array, soarr.length - 2is the index of the second last element in the array. -
In each iteration of the loop, the
ith element of the array is printed out, followed by a space. -
The loop increments
iby 1 in each iteration (++i).
So, the output of the code will be:
21
31
This is because the loop starts at the second element (21) and ends at the second last element (31). The first (11) and last two elements (41, 51) are not printed.
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] + " "); }
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
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 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+" ");}}
Determine output:public class Test{ public static void main(String[] args){ int[] x = {1, 2, 3, 4}; int[] y = x; x = new int[2]; for(int i = 0; i < x.length; i++) System.out.print(y[i] + " "); }}
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.