This is a Java Program which calculates the sum of all elements in an array.
Here initially first element in array and 0 are added the obtained sum is added to 2nd element and so on until the last element in the array.
PROGRAM :
OUTPUT :
Related Programs:
Sum Of Elements in an array ( Cpp )
Here initially first element in array and 0 are added the obtained sum is added to 2nd element and so on until the last element in the array.
PROGRAM :
package codingcorner.in;
import java.util.Scanner;
public class SumOfElementsArray {
public static void main(String[] args) {
int i, n, sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("How many elements do u want to add ?\t");
n = scan.nextInt();
int array[] = new int[n];
for (i = 0; i < n; i++) {
System.out.print("\nEnter number" + (i + 1));
array[i] = scan.nextInt();
}
scan.close();
for (i = 0; i < n; i++) {
sum = sum + array[i];
}
System.out.print("\nThe sum of " + n + " numbers is " + sum);
}
}
OUTPUT :
Java- Sum of elements in an array |
Related Programs:
Sum Of Elements in an array ( Cpp )
No comments:
Post a Comment