# C Program to Reverse a Number Using Function

Howdy readers, today you will learn how to write a program to reverse a number using function in the C Programming language.

The below program prompts the user to enter an integer, then this program reverses the entered integer using function, while loop and Modulus (%) operator.

So, without any delay, letâ€™s begin this tutorial.

## C Program to Reverse a Number Using Function

C Program

```// C Program to Reverse a Number Using Function
#include <stdio.h>
int reverse(int);

int main(){
int num, rev_num, rem;

printf("Enter an integer: ");
scanf("%d", &num);

// Calling out user-defined function
rev_num = reverse(num);

// Displaying result
printf("Reversed number is: %d", rev_num);

return 0;
}

int reverse(int n){
int rem, rev = 0;

while (n != 0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
return rev;
}
```

Output

```Enter an integer: 789
Reversed number is: 987
```

Explanation

```    int num, rev_num, rem;
```

We have declared three int data type variables named `num`, `rev_num`, and `rem`.

```    // Asking for input
printf("Enter an integer: ");
scanf("%d", &num);
```

The user is asked to enter an integer which he/she wants to reverse. This number gets stored in the `num` named variable.

```    // Calling out user-defined function
rev_num = reverse(num);
```

Then, we called the user-defined function named `reverse()` in the main function.

```int reverse(int n){
int rem, rev = 0;

while (n != 0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
return rev;
}
```

Suppose, the user enters a number 789, then:

• 1st While Loop Iteration: while (789 != 0), here the condition is True.
• rem = n % 10 = 789 % 10 = 9
• rev = rev * 10 + rem = 0 * 10 + 9 = 0 + 9 = 9
• n = n / 10 = 789 % 10 = 78
• 2nd While Loop Iteration: while (78 != 0), the condition is True.
• rem = n % 10 = 78 % 10 = 8
• rev = rev * 10 + rem = 9 * 10 + 8 = 90 + 8 = 98
• n = n / 10 = 78 % 10 = 7
• 3rd While Loop Iteration: while (7 != 0), the condition is True.
• rem = n % 10 = 7 % 10 = 7
• rev = rev * 10 + rem = 98 * 10 + 7 = 980 + 7 = 987
• n = n / 10 = 7 % 10 = 0
• 4th While Loop Iteration: while (0! = 0), here the condition is False, so the loop terminates and returns 987 which is the reversed number.
```    // Displaying result
printf("Reversed number is: %d", rev_num);
```

The reverse number is displayed on the screen using `printf()` function.

## Conclusion

I hope after reading this tutorial, you understand how to write a program to reverse a number using a function in the C Programming language.

If you have any queries regarding the program, then let us know in the comment section. We will be pleased to solve all of your queries.