Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in calculation 1+2+3+4...+n?

So I'm assigned to write a program, which asks a number (n) and then makes a addition like this: 1+2+3+4...+n and prints the addition

I keep getting wrong numbers though and can't figure out what is wrong?

import java.util.Scanner;

public class LukusarjanSumma {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int addition = 0;
        System.out.println("Where to?");
        int n = Integer.valueOf(reader.nextLine());
        while (addition <= n){
            addition += addition;
            addition ++;
        } System.out.println("Total is " + addition);
    }
}
like image 875
pakkis26 Avatar asked Dec 18 '25 07:12

pakkis26


1 Answers

You need to differenciate

  • the additition that sums up all
  • a counter that values the increasing index : 1,2,3...n

    int addition = 0;
    int counter = 0;
    System.out.println("Where to?");
    int n = Integer.parseInt(reader.nextLine());
    while (counter <= n) {
        addition += counter;
        counter++;
    }
    System.out.println("Total is " + addition);
    

But the easier would be to use a for loop, this is more logical

int n = Integer.parseInt(reader.nextLine());
for (int i = 0; i <= n; i++) {
    addition += i;
}
like image 85
azro Avatar answered Dec 20 '25 21:12

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!