Advertisement
dinky_moop

Algorithim

Jun 16th, 2022
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. A sample algorithm for Lab 2
  2. Start with the int 2376.
  3. Part 1. Find out how many digits the number has.
  4. Save the number for later.
  5. Initialize a digit counter to 0.
  6. Use a while loop.
  7. Each iteration of the loop should do this.
  8. Divide (integer division) the number by 10. If the quotient is not 0, add 1 to the digit counter.
  9. Here is how the example works in the loop:
  10. Iteration 1: dc is 1. Quotient is 237;
  11. Iteration 2: dc is 2. Quotient is 23.
  12. Iteration 3: dc is 3. Quotient is 2.
  13. Iteration 4: dc is 4. Quotient is 0. Stop the loop.
  14. Let’s call the digit counter dc. Subtract 1 from dc.
  15. Calculate 10^dc. Call this divisor.
  16. Part 2. Use a second while loop to print the digits.
  17. Each iteration of the loop should do this.
  18. Divide (integer division) the number by divisor. This will give one single digit. Print it.
  19. Take the original number and subtract the printed digit *divisor.
  20. Divide divisor by 10.
  21. Keep looping until divisor is 0.
  22. For the example
  23. Subtract 1 from dc. So dc is 3. Calculate divisor as 10^dc, which is 10^3, which is 1000.
  24. Here is how the example works in the loop.
  25. Iteration 1. Divide 2367 by 1000, giving 2. Print 2.
  26. Then multiply 2*1000 giving 2000.
  27. Then subtract: 2367-2000 giving 367.
  28. Then divide divisor by 10. divisor is now 100.
  29.  
  30. Iteration 2. Divide 367 by 100, giving 3. Print 3.
  31. Then multiply 3*100 giving 300.
  32. Then subtract: 267-300 giving 67.
  33. Then divide divisor by 10. divisor is now 10.
  34.  
  35. Iteration 3. Divide 67 by 10, giving 6. Print 6.
  36. Then multiply 6*10 giving 60.
  37. Then subtract: 67-60 giving 7.
  38. Then divide divisor by 10. divisor is now 1.
  39.  
  40. Iteration 4. Divide 7 by 1, giving 7. Print 7.
  41. Then multiply 7*1 giving 7.
  42. Then subtract: 7-7 giving 0
  43. Then divide divisor by 10. divisor is now 0.
  44. Exit the loop because divisor is now 0.
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement