well you can start by counting the no. of digits say n
then in the loop
divisor = 10^(--n)
divide the number by divisor
and update the number as number = number % divisor
cool_zephyr
Junior Poster in Training
75 posts since Apr 2009
Reputation Points: 8
Solved Threads: 9
For Example, if we enter 12300 then these programs output 1 2 3 only and similarly if we enter 1000 then they only output 1.
If you have 1000 and cut off the most significant digit then that becomes 000, which is equivalent to 0. This algorithm does not work when moving from MSD to LSD for that very reason.
To fix it, you can keep an index of the digit and extract it without removing it, or simply work from LSD to MSD and reverse the digits another way (such as with recursion):
#include <iostream>
void reverse_print_digits_r(int value, int base)
{
if (value == 0)
return;
reverse_print_digits_r(value / base, base);
std::cout << value % base << ' ';
}
void reverse_print_digits(int value, int base)
{
if (value == 0)
std::cout << "0";
else
reverse_print_digits_r(value, base);
}
int main()
{
int value;
std::cout << "Enter a value: ";
if (std::cin >> value) {
reverse_print_digits(value, 10);
std::cout << '\n';
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401