I have an assignment to write a recursive function that takes one integer variable and output the integer in reverse order to the screen. I've tried converting it to a char array(c++ "string" class not allowed) but could not get a counter to work. I can reverse an int array with and "upper" and "lower" variable no problem, but I'm stuck without them.

???? reverse(int num) //This is what the assignment calls for.

I'm not looking for anyone to write it for me but I would appreciate some tips.
Thanks in advance.

Dani AI

Generated

A few clarifications and practical tips that extend the helpful ideas from , and .

The middle-zero worry from is a misunderstanding of the printed-digit approach: with input 1034 the recursion prints digits in this order — 4, 3, 0, 1 — producing "4301". A zero digit in the middle is encountered and printed just like any other digit. The only time zeros “disappear” is when you treat the reversed result as an integer value: reversing 1200 as text prints "0021", but as a numeric value the leading zeros are dropped and you get 21.

Negative numbers need one careful step: print the sign once, then operate on the absolute magnitude. Avoid using abs(int) on INT_MIN (it can overflow). A safe pattern is to cast to a wider type (long long), make it positive, then recurse.

If you need the reversed numeric value (not just printed digits), use a small helper that accumulates the result and check for overflow. The wrapper keeps the public signature int reverse_int(int) while the helper does the recursion with an accumulator:

#include <climits>
#include <iostream>

long long reverse_acc(long long n, long long acc = 0) {
    if (n == 0) return acc;
    acc = acc * 10 + (n % 10);
    return reverse_acc(n / 10, acc);
}

int reverse_int(int n) {
    long long t = n;
    bool neg = t < 0;
    if (neg) t = -t;
    if (t == 0) return 0;
    long long rev = reverse_acc(t);
    if (neg) rev = -rev;
    if (rev < INT_MIN || rev > INT_MAX) {
        std::cout << "overflow reversing\n";
        return 0; // or handle as required
    }
    return static_cast<int>(rev);
}

Notes: recursion depth for 32-bit ints is tiny (<= 10 calls). If your assignment forces a single-parameter function and you cannot add helpers, use a wrapper or a static accumulator (but remember to reset it between calls). Also decide up front whether you must preserve printed leading zeros (print digits) or return a numeric result (leading zeros lost).

Recommended Answers

All 8 Replies

Why would you need to use a char array? using int array should be fine.

reverse (num)
   array[count] = num
   count ++
   get a new num
   reverse (num)
   print out array[count]
   count--

It might be logically flawed somewhere..just make sure you have a base case (where you would stop calling the reverse function).

If you're just displaying the reversed thing to the screen, there is no need to store any numbers in any arrays.

Each call to the function will print out a single digit (the digit of number in the units place). If the number is more than 9, the function will call itself with number/10 as the argument. This will recursively print out the number in reverse. When all digits have been printed, the function will stop, and return, due to the above stated call condition.

raw scetch of how I should start to do it:
revprint(int n)
{
if n==0 return
cout<<n%10
revprint(n/10)
}

I'd do it that way too, just I'd add a little if-else-abs() trick to handle n<0 (otherwise it would print -567 reversed as -7-6-5).

something like

if(n<0) {
     cout << "-" << abs(n%10);
     revprint(n/-10);
}
else {
     cout << n%10;
     revprint(n/10);
}

Thanks everyone! I got it working using "n % 10" I was making it too complicated as usual

So you can mark this as solved.

if we give a input which has a digit 0 in between it then loop will end there and output will be incorrect
for eg 1034
the loop will end at the second digit 0 and otput will be incorrect

what to do in this case??

dear i think this would do the trick. its a function, all u need to do is call it in your main program(e.g. flip_integer(12345) will show 54321)

void flip_integer(int number)
{
        int var=0;
        int var2=0;
        var=number;

        var2=var%10;
        var=(var-var2)/10;
        cout<<var2;

        if(var!=0)
        {
        flip_integer(var);
        }
}

hope this helps!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.