In this post, we will know how to reverse a number Using C Programming language.
Reversing a number means interchanging of the digits through which the first digit of the number becomes the last digit and vice versa. For example: 18 after reverse becomes 81.
So, without further ado, let’s begin the tutorial.
C Program To Reverse a Number
// C Program To Reverse a Number int main(){ int n, num = 0, remainder; // Asking for Input printf("Enter an integer: "); scanf("%d", &n); // logic while (n != 0){ remainder = n % 10; num = num * 10 + remainder; n = n / 10; } printf("Reversed Number is %d.", num); return 0; }
Output
Enter an integer: 1234
Reversed Number is 4321.
How Does This Program Work ?
int n, num = 0, remainder;
In this program, we have declared three int data type programs named as n, num and remainder.
// Asking for Input
printf("Enter an integer: ");
scanf("%d", &n);
Then, the user is asked to enter the number. This number will get stored in n named variable.
// logic
while (n != 0){
remainder = n % 10;
num = num * 10 + remainder;
n = n / 10;
}
Now, while loop is used until n != 0 is false.
Inside the loop, the reverse number is computed using:
num = num * 10 + remainder
printf("Reversed Number is %d.", num);
Finally, the reversed number which has been stored in the num variable is displayed as output using printf() function.
Some of the used terms are as follow:
#include <stdio.h> – In the first line we have used #include, it is a preprocessor command that tells the compiler to include the contents of the stdio.h(standard input and output) file in the program.
The stdio.h is a file which contains input and output functions like scanf() and printf() to take input and display output respectively.
Int main() – Here main() is the function name and int is the return type of this function. The Execution of any Programming written in C language begins with main() function.
scanf() – scanf() function is used to take input from the user.
printf() – printf() function is used to display and print the string under the quotation to the screen.
while Loop – In the while loop, the statements inside the body of the while loop keeps executing until it is evaluated to False.
% – It is known as Modulus Operator and provides remainder after division.
// – Used for Commenting in C.
Conclusion
I hope after going through this post, you understand how to reverse a number using C Programming language.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.