-6

So this is what I have:

public static void Positive () {
    int limit = 50;
    for(int i=1; i <= limit; i++){
        System.out.print(i + ", ");
    }
}

That prints out all numbers 1-50 with a loop

How do I return the sum of this using a loop?

Iłya Bursov
  • 20,672
  • 4
  • 30
  • 48

3 Answers3

1

I changed the return type to int.

public static int Positive () {
    int limit = 50;
    int sum = 0;
    for(int i=1; i <= limit; i++){
        System.out.print(i + ", ");
        sum += i;
    }
    return sum;
}
F. Schaaf
  • 73
  • 1
  • 7
1

Another approach

int sum = 0; 

for (int i = 1; i <= 100; i++) {

sum += i; 

}

You havent cleared yet that you want to return the value or just print it from the function so you can use either of the approach in answers of your question. One with int type can return the value and print as well

0

Here is what you can do

public static void Positive () {
int limit = 50;
int total = 0;
for(int i=1; i <= limit; i++){
    total = total + i;
   }
System.out.print(total);
}
Mike Ross
  • 2,753
  • 3
  • 38
  • 81