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);
}
}
You need to differenciate
additition that sums up alla 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With