C Program to Reverse a Number #28

C Program to Reverse a Number

Example to reverse an integer entered by the user. This problem is solved using while loop in this example.
Reverse and integer
To understand this example, you should have the knowledge of following C programming topics:
  • C Programming Operators
  • C Programming while and do...while Loop

Example: Reverse an Integer

#include <stdio.h>
int main()
{
    int n, reversedNumber = 0, remainder;

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

    while(n != 0)
    {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }

    printf("Reversed Number = %d", reversedNumber);

    return 0;
}
Output
Enter an integer: 2345
Reversed Number = 5432
This program takes an integer input from the user. Then the while loop is used until n != 0is false.
In each iteration of while loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by times. 

Comments

Popular

C Program to Display Prime Numbers Between Two Intervals #33

C if...else Statement

C switch...case Statement

C Program to Convert Binary Number to Decimal and vice-versa #39

C Programming Structure and Pointer

C program to Reverse a Sentence Using Recursion #43

Keywords and Identifiers