• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with creating a running total within a for loop  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, this is my first time posting here and I am looking for some help in sorting out this problem "Write a loop that asks the user to enter a number. The loop should iterate 10 times and keep a running total of the numbers entered." So far I have gotten the loop to go ten times and asks and takes the input of the user. The only problem I am having is I can't get a running total within the loop. the code I have so far is



Any help would be much appreciated!
 
Ranch Hand
Posts: 136
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at line 12.

Manish
 
Jd Howard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at line 12.

Manish


I know that it is adding x + 0, what I am asking is how do i add x + 0 and have rt become the answer so that I can add another x to it and so on like that, sorry if I wasn't clear in what I was asking for help with.
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jd Howard wrote:
Have a look at line 12.

Manish


I know that it is adding x + 0, what I am asking is how do i add x + 0 and have rt become the answer so that I can add another x to it and so on like that, sorry if I wasn't clear in what I was asking for help with.


....what I meant to say is that in every loop iteration you are creating and initailising count with some value, so how can you say that
you are maintaining the total....you need to declare count before start of loop and then increment it accordingly inside loop.


Manish
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
manish ghildiyal wrote:you need to declare count before start of loop and then increment it accordingly inside loop....

@Jd: Or indeed use 'rt' the way I suspect you intended to.

Hint: Where do you update the value of 'rt'?

Winston
 
Ranch Hand
Posts: 143
Android Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in line 12 you create a int count.
each time for-loop runs it creates int variable.
So int count = x(entered number) + rt(always 0 till you updates value of it);
returns (entered number).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!