Reputation: 19
i am working on a program to add numbers using an array. I have completed a lot of it but am troubled at the last part adding the actual numbers in the code. Here is my code.
public static void main (String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
for(int i=0;i<n;i++){
x[i]= input.nextInt();
}
}
Upvotes: 0
Views: 135
Reputation: 91
You just need to initial variable with 0 which will have a sum of all values and then while taking a input the values are added into the variable initialized for holding the total values in the same for loop. Given below is the code for the same.
public static void main(String args[]){
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
int total=0;
for(int i=0;i<n;i++){
x[i]= input.nextInt();
total=total+x[i];
}
System.out.println("total"+total);
}
Upvotes: 2
Reputation: 1892
here is a method that will add up your array for you:
public int totalArray(int[] someArray) {
int reply = 0;
for (int value : someArray) reply += value;
return reply;
}
Upvotes: 1
Reputation: 75062
Why not just write some code to add numbers?
import java.util.Scanner;
class X {
public static void main (String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("Enter size of array");
int n= input.nextInt();
int[] x= new int[n];
System.out.println("Enter Array nums");
for(int i=0;i<n;i++){
x[i]= input.nextInt();
}
int sum = 0;
for(int i=0;i<n;i++){
sum+= x[i];
}
// to print the result, uncomment the line below
//System.out.println(sum);
}
}
Upvotes: 1