FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Sum the elements of an array


This program reverses every word of a string and display the reversed string as an output. For example, if we input a string as "Reverse the word of this string" then the output of the program would be: "esrever eht drow fo siht gnirts".

Program 1: No user interaction

class SumOfArray{
   public static void main(String args[]){
      int[] array = {10, 20, 30, 40, 50, 10};
      int sum = 0;
      //Advanced for loop
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

Output


Sum of array elements is:160

Program 2: User enters the array’s elements

import java.util.Scanner;
class SumDemo{
   public static void main(String args[]){
      Scanner scanner = new Scanner(System.in);
      int[] array = new int[10];
      int sum = 0;
      System.out.println("Enter the elements:");
      for (int i=0; i<10; i++)
      {
    	  array[i] = scanner.nextInt();
      }
      for( int num : array) {
          sum = sum+num;
      }
      System.out.println("Sum of array elements is:"+sum);
   }
}

Output


Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

You may also Find this interesting

Program to find leap year

Program to find prime number

Program to find all the prime numbers

Program to Display Area of a Rectangle

Program to Display Area of a Triangle

Program to Display Area of a Circle

Program to Display Vowels and Constant counts