Home > Mobile >  How to store a value that comes from a for
How to store a value that comes from a for

Time:04-14

Hi Im new to Java Im trying to make a counter. What Id like to do is calculate the numbers from 1 to x, for example if x is 5, calculate 1 2 3 4 5.

This is what I wrote, but I get 6 as output instead of 15.

public class Counter {

     public int count (int x){
         int contatore = 0;
         int sum = 0;
         for (int i = 0; i <= x; i  ) {
             sum = i;
             System.out.println(i);
         }
         System.out.println(sum);
        return sum;
     }
}

CodePudding user response:

You need to add i to the sum in each iteration of the loop:

public int count (int x) {
    int contatore = 0;
    int sum = 0;
    for (int i = 0; i <= x; i  ) {
        sum  = i;
        System.out.println(i);
    }
    System.out.println(sum);
    return sum;
}

CodePudding user response:

You are assigning the loop variable to the sum - you need to add it to the sum

 public int count (int x){
     int sum = 0;
     for (int i = 0; i <= x; i  ) {
         sum = sum   i;
     }
    return sum;
 }

As others have noted, you can use the following shorthand notation for addition with assignment.

sum  = i; // equivalent to sum = sum   i;
  • Related