Write a function that calculates the reverse of an integer using recursion.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#include <math.h>
int reverse(int nb)
{
if (nb == 0)
return 0;
// we nultiply the last digits by the number of digits in nb and we add the reverse of nb/10
return ((nb % 10 * pow(10, (int)log10(nb))) + reverse(nb / 10));
}
void main()
{
int nb;
printf("Enter an integer: ");
scanf("%d", &nb);
printf("Reverse of %d = %d", nb, reverse(nb));
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Automata