-4

Pretty much I have to add the numbers a user inputs from an array. so here's what i have.

Scanner input=new Scanner(System.in);

int[] array1=new int[5];
System.out.print("Enter the first number.");
array1[0]=input.nextInt();
System.out.print("Enter the second number.");
array1[1]=input.nextInt();
System.out.print("Enter the third number.");
array1[2]=input.nextInt();
System.out.print("Enter the fourth number.");
array1[3]=input.nextInt();
System.out.print("Enter the fifth number.");
array1[4]=input.nextInt();



System.out.println("The grand sum of the numbers you entered is :"+(array1));
PsyCode
  • 644
  • 5
  • 14
Robert
  • 1
  • 1

3 Answers3

2
int sum = 0;
for(int i: array1)
    sum += i;
System.out.println("The grand sum of the numbers you entered is :" + sum);
isomarcte
  • 1,981
  • 12
  • 16
0

First start with definition of Array

  1. An array is a container object that holds a fixed number of values of a single type.
  2. The length of an array is established when the array is created.
  3. After creation, its length is fixed.

Example :

enter image description here

So lets see what you process you need to do your addition here ?

Loops

The definition of loops :

If you need to execute some block of code more than one time or iterate over a range of values, loop is used.

There 3 different ways of looping in Java

 Name                      Synatx

1. for loop for(initialization; Boolean_expression; update){ //Statements}

  1. while loop while(Boolean_expression){//Statements}

  2. do while loop do{//Statements }while(Boolean_expression);

Based on the definition of loop in Java, you need to use looping here because you want to do addition as many times as necessary

Lets solve your issue with while loop

you need a accumulator variable like

int sume = 0;

Follow the syntax of for loop

for(initialization; Boolean_expression; update)
{
   //Statements
}

so your whole code become :

 int sum = 0;
 for(int i=0; i< array1.length; i++){
      sum = sum + array1[i]
   }

you will start from index zero and keep adding till index is going to be less than length of array why because array index starts from zero in java. Inside for loop, you add the content of each elements to accumulators in order to derive the sum that you are looking for .

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
  • Nice work, but that answer is perhaps a bit, well… “over-engineered”. Small typo: what you call a `while` loop actually is a `for` loop. Finally, I think the for-each loop would be most appropriate in this case. We should avoid doing manual index arithmetic whenever possible. – 5gon12eder Sep 14 '14 at 23:45
-1

I had to use array1[0]+array1[1]+array1[2]+array1[3]+array1[4]

user229044
  • 232,980
  • 40
  • 330
  • 338
Robert
  • 1
  • 1