Implementation of reverse(int) Function
To implement a reverse(int) function in C that reverses the digits of an integer, you can use a simple iterative approach. Here's an example of how to implement the reverse()
function:
Example:
#include <stdio.h>
// Function to reverse the digits of an integer
int reverse(int num) {
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
return reversed;
}
int main() {
int number = 12345;
int reversedNumber = reverse(number);
printf("Original number: %d\n", number);
printf("Reversed number: %d\n", reversedNumber);
return 0;
}
In this example:
- The
reverse()
function takes an integer num
as its parameter and initializes a variable reversed
to 0.
- Inside the
while
loop, the function repeatedly extracts the last digit of num
using the modulo operator %
and adds it to the reversed
variable. It then removes the last digit from num
by dividing it by 10.
- The process continues until
num
becomes 0, at which point the reversed integer is calculated.
- In the
main()
function, a number (12345 in this case) is passed to the reverse()
function, and the reversed number is stored in the reversedNumber
variable.
- Finally, the program prints both the original and reversed numbers.
Output:
Original number: 12345
Reversed number: 54321
You can use this reverse()
function to reverse the digits of any integer by passing it as an argument to the function.