Java Program to Find the Sum of First N Elements of the Array

In the previous article, we have seen Java Program to Print All the Positive Elements in an Array

In this article we are going to see how to find sum of first n elements of an array.

Java Program to Find the Sum of First N Elements of the Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the sum of first n elements.

Method-1: Java Program to Find the Sum of First N Elements of the Array By Static Initialization of Array Elements

Approach:

  • Initialize sum = 0.
  • Iterate over the array up to nth element and add the current element to sum.
  • Return sum.

Program:

public class Main 
{
    public static void main(String[] args) 
    {
        // initialize the array
        int[] arr = { 17, 21, 3, 23, 12, 45, 123, 235 };
        int n = 6;
        // calling the method and printing result
        System.out.println("Sum of first "  + n + " elements of the array is: " + findSum(arr, n));
    }

    static int findSum(int[] arr, int n) 
    {
        int sum = 0;
        // looping over the array till n and updating sum variable
        for (int i = 0; i < n; i++) 
        {
            sum += arr[i];
        }
        return sum;
    }
}

Output:

Sum of first 6 elements of the array is: 121

Method-2: Java Program to Find the Sum of First N Elements of the Array By Dynamic Initialization of Array Elements

Approach:

  • Create scanner class object.
  • Ask use length of the array.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Iterate over the array.
  • Initialize sum = 0.
  • Iterate over the array up to nth element and add the current element to sum.
  • Return sum.

Program:

import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        // initialize the array
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of array: ");
        int m = sc.nextInt();
        // initialize array with size n
        int[] arr = new int[m];
        // take input from user for array elements
        System.out.print("Enter array elements: ");
        for (int i = 0; i < m; i++) 
        {
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter the position up to sum is to be calculated: ");
        int n = sc.nextInt();
        // calling the method and printing result
        System.out.println("Sum of first "  + n + " elements of the array is: " + findSum(arr, n));
    }

    static int findSum(int[] arr, int n) 
    {
        int sum = 0;
        // looping over the array till n and updating sum variable
        for (int i = 0; i < n; i++) 
        {
            sum += arr[i];
        }
        return sum;
    }
}

Output:

Enter the size of array: 5
Enter array elements: 1 2 3 4 5
Enter the position up to sum is to be calculated: 3
Sum of first 3 elements of the array is: 6

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Related Java Programs: