3

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);
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
pakkis26
  • 53
  • 2
  • Why do you increment `addition` by both itself and 1? You're effectively writing `addition = 2 * addition + 1;`. – Andy Turner Mar 19 '20 at 11:16
  • 3
    http://www.jepspectro.com/htmDoc/Little%20Gauss%20formula.htm – luk2302 Mar 19 '20 at 11:18
  • Actual for this primitive level of questions, I'd like to suggest that people should try to simulate their program with pencil and paper (if they are seemingly unable to use a debugger). It seems the user took little to no effort trying to solve the problem before asking. – U. Windl Mar 19 '20 at 11:31

3 Answers3

3

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;
}
azro
  • 53,056
  • 7
  • 34
  • 70
1

Using a more modern solution, you could use something along the lines of this:

import java.util.stream.IntStream;

public class Test {

    public static void main(String[] args) {
        int n = Integer.parseInt("10");
        int sum = IntStream.range(0, n).reduce(n, (a, b) -> a  + b);
        System.out.println("Total is " + sum);
    }
}

Obviously in my example it doesn't take any input from the CLI, it's just a fixed value, but I'm certain you get the idea. You may be asking why I like solution over the likes of a more traditional for loop purely because of how small & concise it is, I just generally find it much easier to read & maintain.

Not to mention that a solution like this introduces you to some concepts related to functional programming, such as immutability. While cools guys like Eric Elliott may do a lot of tutorials in JavaScript, the principles are transferable to practically any language! :)

A little bit of theory

While functional programming rocks, the precise example I've provided may not be the most appropriate if your core target is performance. In this case, it is better to use a more traditional solution, but given it's such a primitive application/piece of code, I think it's fine.

From a computational complexity perspective, from a speed & branching perspective, it's roughly the same as a traditional solution, however, just by using a stream, never mind creating the range, it's likely using more memory than a simple for loop. But you could also argue that the compiler would do such a great job that it may actually implement this as a traditional for loop.

With my solution, it does 9 iterations, if you were to use a for loop like the one @azro provided, then the code would result in 10 iterations, so that's also something to think about I guess! :)


Edit

I should note that this solution will work with Java 8+.

JO3-W3B-D3V
  • 2,124
  • 11
  • 30
  • Appreciate your time to answer such an idiomatic question as mine! But since I've only been familiar with Java for like 4 hours, that goes way over the top right now (:D), but will definitely keep your comment in mind for future purposes! – pakkis26 Mar 19 '20 at 11:56
  • @pakkis26 I assumed that this was the case, hence why I decided to include a little bit of theory, not so much that it would blow your mind or anything. If you need help learning, feel free to give me a message! :) – JO3-W3B-D3V Mar 19 '20 at 11:57
  • @pakkis26 It may also be worth looking into the likes of [lambda expressions](https://www.baeldung.com/java-8-lambda-expressions-tips). – JO3-W3B-D3V Mar 19 '20 at 11:59
0

You need two variables, one for the sum and the other for the current number to be added:

    Scanner reader = new Scanner(System.in);
    int sum = 0;
    int i = 0;
    System.out.println("Where to?");
    int n = Integer.valueOf(reader.nextLine());
    while (i <= n){
        sum += i;
        i++;
    } System.out.println("Total is " + sum);
Eran
  • 387,369
  • 54
  • 702
  • 768