0

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);

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

This is a lot nicer than my half-assed attempt.
Actually, this isn't that much different from your original answer.
Thank You! Looking at this now, it makes total sense.
If this answer solves your problem, please consider accepting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.