### Trying to print one digit at a time using a specific algorithm Im trying to print on digit at a time for example, 123 would be
1
2
3

using an algorithim my proffessor is telling us to use but mines ends up printing 123 as

1
12
123.

Any close on what to do?

My code

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253`` `````` #include #include using namespace std; void digit (int num) { int num2 = num; int dc = 0; int x =0; int divisor = 0; { num=num/10; dc++; } divisor = pow(10, dc); while(dc < num) { num=num/10; dc++; } divisor = pow(10, dc); while(divisor > 0) { x = num2/divisor; cout << x << endl; x=x*divisor; x=num2-x; divisor=divisor/10; } } int main () { int num = 0; cout << "Please enter a number: "; cin >> num; digit(num); cin.ignore(); cin.get(); return 0; } ``````
Last edited on Here is the link for the algorithm
https://pastebin.com/kBe9qiVH ``12345678910111213141516`` ``````#include #include int main() { std::cout << "Enter an number: "; int num { }; std::cin >> num; std::string num_str { std::to_string(num) }; for (const auto& itr : num_str) { std::cout << itr << '\n'; } }``````
 ```Enter an number: 123 1 2 3``` number % 10 gets you the 1s place.

So if you combine % and /, you can get each digit (but this is actually backwards).

So it might be easier if you write a function to reverse the digits of an integer, then loop by printing (number % 10) then doing (number = number / 10) while number > 0. Thanks Ganado!!! It works now :) ``12345`` ``````void print( unsigned long long number ) { std::cout << number << '\n' ; if( number > 9 ) print( number/10 ) ; }``````

http://coliru.stacked-crooked.com/a/2c94fe5d49e44103 ``12345678910111213141516`` ``````#include void print( unsigned long long n ) { if ( n > 9 ) print( n / 10 ); std::cout << n % 10 << '\n'; } int main() { print( 1234567890112233ull ); }`````` ```1 2 3 4 5 6 7 8 9 0 1 1 2 2 3 3```

But no, this is nothing like the (very longwinded) algorithm that your teacher required.
Last edited on Here is the link for the algorithm

OMG - what are they teaching these days...
Topic archived. No new replies allowed.