Bookmark Topic Watch Topic
  • New Topic

taking an online self paced course and stuck  RSS feed

 
Chadley Vidal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Report post to moderator
I just cant see how to use the user input to get the same result.
I know I need to somehow loop through the value the user enters and and increment sum .... just cant see it

Can you complete the exercise below such that it prints the sum of 1 to n numbers. The int n is taken as input from the user. Use a for loop to complete this exercise.
You will need a variable where you can store the new sum from each iteration. We have provided a variable called sum of the type int, for this purpose.



Appreciate help
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
The best way to go about this would be to forget about reading and validating user input from a command-line for the time being. you should focus on the algorithm that calculates the sum of 1 to N integers first. Let's say you'd have to calculate the sum of all integers between 1 thru 10, how would you go about it?
 
Chadley Vidal
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Report post to moderator
Well. If I did it on a piece of paper,

I write down all the numbers one per line
then add them together.






and the results should be ..


the value of count is 1
the value of sum is 1
the value of count is 2
the value of sum is 3
the value of count is 3
the value of sum is 6
the value of count is 4
the value of sum is 10
the value of count is 5
the value of sum is 15
the value of count is 6
the value of sum is 21
the value of count is 7
the value of sum is 28
the value of count is 8
the value of sum is 36
the value of count is 9
the value of sum is 45
the value of count is 10
the value of sum is 55
55
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
Right, now the first step to making that dynamic to support a user provided upper bound, is to replace the hard coded 10 in the termination expression of the for-loop with an int variable.
That variable has to be assigned a value somehow. You could do that interactively from the command-line as you have in your opening post: n.
Put those two together and you've got the basics finished. All that's left is validating the input - I assume the "Enter an int from 5 to 100" was part of the assignment.
So in between reading the user input, and using it in the for-loop, you should validate that it doesn't violate the lower and upper bound.
 
Consider Paul's rocket mass heater.
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!