In: Computer Science
Java Programming
I need an application that collects the user input numbers into an array and after that calls a method that sums all the elements of this array. and display the array elements and the total to the user.
The user decides when to stop inputting the numbers.
Thanks for your help!
Source Code in text format (See below images of code for indentation):
import java.util.*;
/*class definition*/
public class ArraySum
{
/*main method*/
public static void main(String[] args)
{
/*Scanner class to read input from the user*/
Scanner read=new Scanner(System.in);
/*variables*/
int n,sum=0,i;
/*read size of the array from user*/
System.out.print("Enter the size of the array: ");
n=read.nextInt();
/*declaration of array*/
int[] a=new int[n];
/*read elements from the user*/
System.out.println("Enter elements of array:");
for(i=0;i<n;i++)
a[i]=read.nextInt();
/*display array*/
System.out.print("The array is: ");
for(i=0;i<n;i++)
System.out.print(a[i]+" ");
/*method call*/
sum=sumArray(a);
/*print sum*/
System.out.print("\nSum of array elements is: "+sum);
}
/*method definition*/
public static int sumArray(int[] a)
{
/*calculate sum*/
int sum=0,j;
for(j=0;j<a.length;j++)
sum+=a[j];
/*return sum*/
return sum;
}
}
Source Code:
Output: