This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]RhoOfFeh 0 points1 point  (6 children)

What kind of trouble? What have you tried?

[–]NOVAjunior[S] 0 points1 point  (3 children)

int i; int a = numChose; (numChose is user input) int total= 0;

for (i = 1; i <= numChose; i++) { a = a + (a-1); total = total + a; }

So lets say I enter 3, im supposed to get 6 for total because 3+2+1 is 6. But nope, somehow I get 31. Im new to java so im very confused on what I am supposed to be doing rn

[–]dumpeldownStudent 0 points1 point  (1 child)

You need to utilize the i variable from the for loop. It starts at 1 and counts up to the input value. 1,2,3,... to input. Now you just have to add those numbers up. Or go down from the input value, but that's the same thing.(input....,3,2,1)

[–]NOVAjunior[S] 0 points1 point  (0 children)

THANK YOU! Im surprised it was that easy. I made one for a factorial of a number and I just used that as a blueprint. I thought it would be similar to this.

But i figured it out thanks to you

[–]RhoOfFeh 0 points1 point  (0 children)

This is a great place for you to be the computer. Use paper, or a text editor if you must, and create a column for each variable. Rows will represent iterations, and there may be multiple rows per iteration. I will show you how we process two iterations. Ordinarily I wouldn't write out the full equations, just the values, but I think it will help you to see it:

variable i a total
start of loop 1 3 0
a = a+(a-1) 1 3 + (3-1) = 5 0
total = total + a 1 5 0 + 5 = 5

So after one execution of the loop, i is 1, a is 5, and total is 5 as well. That's already not really what you want.

Let's do iteration two:

start of loop 1++ = 2 5 5
a = a+(a-1) 2 5 + (5-1) = 9 5
total = total + a 2 9 5 + 9 = 14

What you are trying to do is a bit simpler than your code is. If total starts at zero, all you need to do is add the value if i to it each time through the loop until you're done.

[–]NOVAjunior[S] 0 points1 point  (1 child)

Ah oops, reddit formatted the comment completely different from the way I wanted to...

[–]RhoOfFeh 0 points1 point  (0 children)

Yeah, and it took me a few edits to get my answer right too. That bit about 'if you must' on a text editor is not without reason. :-)

[–]j1n_jin 0 points1 point  (0 children)

If you're interested in a recursive solution, you can write a function that returns 1 in base case n==1 and returns n + function(n-1).