Guys, help, please. Learning recursion in the university). It is necessary to write a program that prints the decimal notation of the entered natural number, using only the operation of printing numbers from 0 to 9. I thought to get the first number, output it, then delete it from the number and again into this function, but it does not work at all ..

    3 answers 3

    The option is simpler than suggested by @DreamChild .

    void print_num(uint32_t num) { if (num) { print_num(num / 10); cout << num % 10; } } 

    Try on Ideone

    • truly elegant) - DreamChild
    • one
      Only here 0 will not print (although, 0 is not a natural number). - avp
    • @avp prints - nanotexnik
    • And what is uint32_t? int does not give a ride? - inferusvv
    • @ inferus-vv give a ride. You can see the types here. En.cppreference.com/w/cpp/header/cstdint - IronVbif

    Try this:

     void PrintNum(unsigned int num) { /* не стал заморачиваться с конвертацией int => string, поэтому взял библиотечную из С++11 */ string str = std::to_string(num); cout << str[0]; int length = str.length(); if(length == 1) { cout << endl; return; } num = num % (int)pow(10, length - 1); PrintNum(num); } 
       void print_num(int32_t n){ if (n < 0) { cout << "-"; n = -n; } if (n > 9) { print_num(n / 10); } cout << n % 10; } 
      • one
        For INT_MIN will not work. Recently discussed here . - Actually, it is not for nothing that natural numbers are sounded in the problem to the question. - avp
      • if you really climb into ... then this exercise is from K & R in which the case of signed min int is considered separately in the same place where atoi is qulinxao
      • @qulinxao, the more people will hear at least something about INT_MIN == -INT_MIN , the less glitches will be in work programs. - avp
      • It is worth remembering the basic rule of Unix programming is 80% better now than 100% sometime in the future. - qulinxao
      • Moreover, the error (in case of a random choice of the number) will occur approximately 1 time for 4294967295 calls (much less frequently than 1 out of 5 recommended). - However, this case is rather a matter of principle, and not, say, the applicability of hash tables in the management of traffic lights. - avp