16 May 2024

Find The Sum of Array

FIND THE SUM OF ARRAY

Calculating the sum of elements in an array is a common programming task. In this post, we will explore how to achieve this in Java step by step, using a simple and efficient approach.

The Problem

Given an array of integers, we want to find the sum of all the elements. The user provides the number of elements followed by the values of the elements.

Step-by-Step Explanation

  1. Importing Required Package:

    • The java.util.* package is imported to use the Scanner class for input handling.
  2. Reading Input:

    • Scanner sc = new Scanner(System.in);: A Scanner object is created to read user input.
    • int n = sc.nextInt();: Reads the number of elements in the array (size of the array).
  3. Calculating the Sum:

    • The for loop runs n times, reading each number using sc.nextInt() and adding it to the sum variable.
  4. Displaying the Result:

    • The final sum is printed using System.out.print(sum);.

CODE

import java.util.*;

class HelloWorld {

    public static void main(String[] args) {

        int sum=0;

        int n=sc.nextInt();

        for(int i=0;i<n;i++){

            sum+=sc.nextInt();

        }

        System.out.print(sum);

    }

}

No comments:

Post a Comment