C Program To Reverse A Number

Number reversing is an important topic for every beginner. It will help you to understand the basic loop functions and positioning. Here in this article, we will explain how to reverse a number using the C program. We are also going to share the source code with you.

C Program To Reverse A Number

Basic principle

The basic principle of number reversing is, take a number as input then reverse it and print that as output. For example, if the user inputs the number 123 then the output should be 321. The program should take input from the user then it should reverse the number and then show it in output.

Example Code

#include <stdio.h>
int main() {
    int num;
    int tem_var;
    int sum = 0;
    int remainder;

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

    tem_var = num;

    while (tem_var != 0)
    {
        remainder = tem_var % 10;
        sum = sum * 10 + remainder;
        tem_var = tem_var / 10;
    }
    printf("Reversed number = %d", sum);
    return 0;
}

Output:

Enter an integer: 123
Reversed number = 321
Process returned 0 (0x0)   execution time : 3.500 s
Press any key to continue.

Code Explanation

At first, take 4 variables 1 variable for input number, 1 variable for temporary variable, 1 variable for the initial situation, 1 variable for the remainder. Using scanf() take the user input and store it inside a variable.

Store the user input number inside a temporary variable. Then write the while loop where it will work only if the temporary variable is not 0. At the end print the sum.

Read more: C Tokens in C Programming Language

Use cases of  number reversing programs

You can use this in many places like encryption. For example, you can take the user input and reverse it and store it. It is actually one type of encryption. But in real life, we need many programs and steps to encrypt any data. Test your c programming skill by solving problems.
Post a Comment (0)
Previous Post Next Post