-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Wednesday, August 5, 2020

Java Program To Sum the elements of the Array Entered By The User

  • August 05, 2020
  • by

Java Program To Sum the elements of the Array Entered By The User

In this Java Program, we sum up all the elements of the array entered by the user.

Array is a data structure consisting of collections of elements each identified by atleast one array index or key. 

E.g. If you want to store 5 numbers in an array,

        datatype arrayname [arraysize];

         int a[5];

Step 1 : Import java.util.Scanner Class

Step 2 : Create the object of the Scanner Class

Step 3 : Create and Initialize array

Step 4 : Create variable sum and initialize it to zero

Step 5 : Ask the user to enter the elements by using println method 

Step 6 : Apply for loop where i is equal to 0, i is less than 10 and increment i

Step 7 : Store the user entered elements in the array of i

Step 8 : Apply advanced for loop where num : array

Step 9 : Add sum and num and save its result in the variable sum

Step 10 : Print the Sum of the array elements.

Program :

import java.util.Scanner;
public class SumArray2 
    {
        public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            int[] array = new int[10];
            int sum = 0;
            System.out.println("Enter the elements:");
            for(int i = 0; i<10; i++)
            {
                array[i] = sc.nextInt();
            }
            for(int num : array)
            {
                sum = sum + num;
            }
                System.out.println("Sum of array elements is:"+sum);
           
        }
    
}

Output :

Enter the elements:
1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

For Execution of the same do visit my YouTube Channel :





A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages