Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- A sample algorithm for Lab 2
- Start with the int 2376.
- Part 1. Find out how many digits the number has.
- Save the number for later.
- Initialize a digit counter to 0.
- Use a while loop.
- Each iteration of the loop should do this.
- Divide (integer division) the number by 10. If the quotient is not 0, add 1 to the digit counter.
- Here is how the example works in the loop:
- Iteration 1: dc is 1. Quotient is 237;
- Iteration 2: dc is 2. Quotient is 23.
- Iteration 3: dc is 3. Quotient is 2.
- Iteration 4: dc is 4. Quotient is 0. Stop the loop.
- Letβs call the digit counter dc. Subtract 1 from dc.
- Calculate 10^dc. Call this divisor.
- Part 2. Use a second while loop to print the digits.
- Each iteration of the loop should do this.
- Divide (integer division) the number by divisor. This will give one single digit. Print it.
- Take the original number and subtract the printed digit *divisor.
- Divide divisor by 10.
- Keep looping until divisor is 0.
- For the example
- Subtract 1 from dc. So dc is 3. Calculate divisor as 10^dc, which is 10^3, which is 1000.
- Here is how the example works in the loop.
- Iteration 1. Divide 2367 by 1000, giving 2. Print 2.
- Then multiply 2*1000 giving 2000.
- Then subtract: 2367-2000 giving 367.
- Then divide divisor by 10. divisor is now 100.
- Iteration 2. Divide 367 by 100, giving 3. Print 3.
- Then multiply 3*100 giving 300.
- Then subtract: 267-300 giving 67.
- Then divide divisor by 10. divisor is now 10.
- Iteration 3. Divide 67 by 10, giving 6. Print 6.
- Then multiply 6*10 giving 60.
- Then subtract: 67-60 giving 7.
- Then divide divisor by 10. divisor is now 1.
- Iteration 4. Divide 7 by 1, giving 7. Print 7.
- Then multiply 7*1 giving 7.
- Then subtract: 7-7 giving 0
- Then divide divisor by 10. divisor is now 0.
- Exit the loop because divisor is now 0.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement