• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please critic, rate or give some helpful advice

 
Dondon Tan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, i'm new to this forum. I'm not a programmer by trade in fact i'm still a newbie but can you please rate or critic the way i write codes.

Problem #1 Create a program which will accept integers between 0 - 1000. The program will then add each integer.

Example

Given = 932 Result = 14
Given = 432 Result = 9

This is my answer


 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!


This will work as long as you get numbers between 0 and 1000. What will you do if your requirements change, and you should do the same with numbers between 0 and 10.000? And then with numbers between 0 and 100.000? And so on?

One tip: you can do this with a loop and solve it for all kinds of numbers. I'll show you how with your example.

Start: number left = 432, sum = 0
Iteration 1: number left = 43, sum = 2
Iteration 2: number left = 4, sum = 2 + 3
Iteration 3: number left = 0, sum = 2 + 3 + 4
Nothing more to add so stop the loop.

Let's now use a larger number:
Start: number left = 987654321, sum = 0
Iteration 1: number left = 98765432, sum = 1
Iteration 2: number left = 9876543, sum = 1 + 2
...
Iteration 8: number left = 9, sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
Iteration 9: number left = 0, sum = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
Nothing more to add so stop the loop.

Now I'm sure you can translate this into code.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34860
369
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dondon,
Welcome to CodeRanch!

While your code is fine, you asked for a code review - so two tips:

1) You don't appear to use x3 and x4 so I would recommend removing them. If this were a real program that someone had to maintain, it would be clearer.
2) I would name x1 "firstDigit" or something that made it clearer what it is.
 
Dondon Tan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Rob Prime: Thanks for the tip! Not at my house at the moment. But i'll work on the code as soon as i arrive. I think i'll try the for loop on this one.

@Jeanne Boyarsky: Thanks! i completely forgot about x3 and x4.. LOL, as for naming my variables, you do have a point. Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic