pTutorial

New way to learn Programming

Java Sum Of Array

The Following Java program add the array element. We use for loop to perform addition with the help of length. It is not a user define program so you cannot enter the length of array and also array element.

Java Sum Of Array Example

package pTutorial;
public class SumArray {
	
	public static void main(String[] s) {
		
		// number is a array variable
		int[] number = new int[]{ 20, 10, 20, 10, 20};
		 
		int sum = 0;
		 
		for (int i=0; i < number.length ; i++) {
			sum = sum + number[i];
		}
		 
		System.out.println("Total value of array : " + sum);
		
	}

}

Output

Total value of array : 80

Java User define Sum Array

This is a user define Java program to perform addition of array element. We use scanner class and scanner class nextInt() method to take input from user.

package pTutorial;

import java.util.Scanner;

public class SumArray {
	
	public static void main(String[] s) {
            
                System.out.println("Enter the no. of element");

                Scanner num=new Scanner(System.in);

                int temp = num.nextInt();

                int[] number = new int[temp];
                
                System.out.println("Enter "+temp +" numbers");
                
                    for(int l=0;l<number.length;l++)
                
                    {
                    
                        number[l]= num.nextInt();
                    }   
		int sum = 0;
		 
		for (int i=0; i < number.length ; i++) {
			sum = sum + number[i];
		}
		 
		System.out.println("Total value of array : " + sum);
		
	}

}

Output

Enter the no. of element
2
Enter 2 numbers
10
10
Total value of array : 20

See Also


QUOTES OF THE DAY

The basis of all progress is self-reliance

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER