So I cannot figure out how to do this ?the starter code is in the link

Viewed 34

Write a method named addUp that receives an integer as an argument, then returns the sum of all positive numbers up to and including that number.

Examples:

addUp( 5 ) --> 1 + 2 + 3 + 4 + 5 --> 15
addUp( 7 ) --> 1 + 2 + 3 + 4 + 5 + 6 + 7 --> 28
addUp(10 ) --> 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 --> 55

enter link description here

2 Answers

From Java 8 and later versions you can use IntStream to sum range of integer.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        System.out.println(addUp(7));
    }

    public static int addUp(int num){
        return IntStream.rangeClosed(1,num).sum();
    }
}
public class MyClass {
    public static int addUp(int number) {
        int sum = 0;
        for (int i = 1; i <= number; i++) {
            sum += i;
        }
        return sum;
    }

    public static void main(String args[]){
        System.out.println(addUp(5));
    }
}
Related