Reputation: 1
I am working on a program where a user gives two numbers. The first is the number that the counter will count up to. The second is the increment it will do so. The program has a starting number of one and should add all the numbers together that add up the first given number. For example, The user inputs numbers 7 and 2. So the program should do the following: 1+3+5+7 and would equal 16. I cannot figure out what I am doing wrong with my program.
System.out.print("Please enter your first positive number: ");
int n1 = user.nextInt();
System.out.print("Please enter your second positive number: ");
int n2 = user.nextInt();
int sum = 1;
while(sum <= n1)
{
sum += n2;
}
System.out.println("Sum = " + sum);
Upvotes: 0
Views: 302
Reputation: 11822
At the moment, you are stopping when your sum exceeds n1
. And for each loop, you are adding n2
, not the last value incremented by n2
.
Try this which uses a for loop to loop through the real increment values (which increase each iteration):
System.out.print("Please enter your first positive number: ");
int n1 = user.nextInt();
System.out.print("Please enter your second positive number: ");
int n2 = user.nextInt();
// start your sum at zero
int sum = 0;
// loop increasing the increment value until it exceeds the users input
for(int increment = 1; increment <= n1; increment += n2) {
sum += increment;
}
System.out.println("Sum = " + sum);
Upvotes: 2