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.

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, learning, and sharing knowledge.