fork(1) download
  1. #include <iostream>
  2.  
  3. int first_digit( unsigned int number )
  4. {
  5. std::cout << "number: " << number << '\n' ;
  6.  
  7. if( number < 10 ) // the number consists of a single digit
  8. {
  9. std::cout << "there is just one digit, return it\n" ;
  10. return number ; // just return that digit
  11. }
  12.  
  13. // the number consists of two or more digits
  14. // number/10 gives the number with the last (right-most) digit removed
  15.  
  16. return first_digit( number/10 ) ; // call recursively with one less digit
  17.  
  18. // each time through the recursion, we reduce the number of digits by one.
  19. // Eventually, when there is just one digit left,
  20. // that is the first (left-most) digit and we return that
  21. }
  22.  
  23. int main()
  24. {
  25. std::cout << first_digit(12345678) << '\n' ;
  26. }
  27.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
number: 12345678
number: 1234567
number: 123456
number: 12345
number: 1234
number: 123
number: 12
number: 1
there is just one digit, return it
1