What will be the output of the following Java program? public class SumOfArray { public static void main(String[ ] args) { int [ ] arr = new int [ ] {1, 2, 3, 4}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println("Sum of all the elements of an arry: " + sum); } }
What will be the output of the following Java program? public class SumOfArray { public static void main(String[ ] args) { int [ ] arr = new int [ ] {1, 2, 3, 4}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println("Sum of all the elements of an arry: " + sum); } } Correct Answer <span style="">Sum of all the elements of an array: 10</span>
The correct answer is option 2.
Concept:
An array in Java is an object that contains elements of the same data type. Furthermore, the items of an array are kept in a single memory address. It's a data structure where we save items that are comparable. In a Java array, we can only hold a fixed number of items.
The given Java code is,
public class SumOfArray
{
public static void main(String args)
int arr = new int {1, 2, 3, 4};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr; }
System.out.printIn("Sum of all the elements of an arry: " + sum); }
}
Explanation:
"arr" is an integer array it has four elements like,
arr=1;
arr=2;
arr=3;
arr=4;
And initially, the sum has zero, and each iteration of the for-loop adds to the sum. At end of the sum, the variable has added all elements in an integer arr of four elements.
sum=1+2+3+4;
And sum=10
Prints like Sum of all the elements of an array: 10 as output.
Hence the correct answer is the Sum of all the elements of an array: 10.