sum of one-Dimensional array elements in java
One-Dimensional Arrays is one of the basic and the commonly asked questions in the Technical Interviews.
Problem Statement:
Java program to read ‘N’ array elements from One dimensional Array and print the sum of all array elements
Solution Approach:
What we need to consider here
- One-Dimensional Array with array size
- Array Element Iteration
- Add the array element
- Display the sum of all array elements
The below given problem provides the technical solution of reading array N elements and printing the array element sum
package com.java.planforexams.array; import java.util.Scanner; public class OneDimArrayElementSum { public static void main(String args[]) { // Scanner object for eading User Input Scanner scan = new Scanner(System.in); int count,arrayElemntSum = 0; // Receive the Array Element Count from User System.out.print("Provide the Array Element Count : "); // Receive the Array Elements from User. count = scan.nextInt(); int arrayInputFromUser[] = new int[count]; System.out.println("Enter the elements:"); // Iterate the array elements for (int incr=0; incr<count; incr++) { arrayInputFromUser[incr] = scan.nextInt(); } for( int arrayElementValue : arrayInputFromUser) { arrayElemntSum = arrayElemntSum + arrayElementValue; } // print the sum of all array elements. System.out.println(" ::::Sum of One Dimensional N Array Elements is :::::" +arrayElemntSum); } }
One-Dimensional Array Program Output:
Provide the Array Element Count : 4
Enter the elements:
23
23
23
23
::::Sum of One Dimensional N Array Elements is :::::92
Leave a Reply