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
Importing Required Package:
- The
java.util.*package is imported to use theScannerclass for input handling.
- The
Reading Input:
Scanner sc = new Scanner(System.in);: AScannerobject is created to read user input.int n = sc.nextInt();: Reads the number of elements in the array (size of the array).
Calculating the Sum:
- The
forloop runsntimes, reading each number usingsc.nextInt()and adding it to thesumvariable.
- The
Displaying the Result:
- The final sum is printed using
System.out.print(sum);.
- The final sum is printed using
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