Select Page

# C Program to Reverse a Number

by | Jan 29, 2023 | C, C Programs

Home » C » C Programs » C Program to Reverse a Number

## Introduction

In this program, you will learn to reverse the digits of the integer value entered by the user.

For example, if the number is 98542, then this code will reverse the number, and the output will be 24589.

To understand the program, learn the following basic concepts of C programming

1. C programming operators

2. C while and do-while loop

## Program

```#include<stdio.h>
int main()
{
int x;
printf("enter a number:");
scanf("%d",&x);
int rem=0; // rem is used for the remainder
int z=0;
while(x>0)
{
rem=x%10;
z=z*10+rem; // formation of reversed integer
x=x/10; // elimination of last digit
}
printf("Reversed number is \n%d",z);
return 0;
}```

## Output ## Explanation

‘x’ will store the integer entered by the user.

int rem=0; ‘rem’ variable is initialized with 0 value to find the remainder.

int z=0; ‘z’ variable is initialized with 0 value to hold the reversed integer.

The value of ‘x’ is 123456

while(x>0)

the above condition is true

rem=x%10; this will return rem=123456%10=6

z=z*10+rem;

Since z is 0 therefore from the above statement, z=0*10+6=6

x=x/10; the value of ‘x’ is updated to 123456/10=12345 thus vanishes the last digit.

Again the condition in the while loop will become true and the same procedure will take place for x=12345

rem=12345%10=5

z=6*10+5=65

x=12345/10=1234

Again the condition in the while loop will become true and the same procedure will take place for x=1234

rem=1234%10=4

z=65*10+4=654

x=1234/10=123

Again the condition in the while loop will become true and the same procedure will take place for x=123

rem=123%10=3

z=654*10+3=6543

x=123/10=12

Again the condition in the while loop will become true and the same procedure will take place for x=12

rem=12%10=2

z=6543*10+2=65432

x=12/10=1

Again the condition in the while loop will become true and the same procedure will take place for x=1

rem=1%10=1

z=65432*10+1=654321

x=1/10=0

Now the condition in the while loop becomes false and the loop terminates.

Thus, the final value of ‘z’ is 654321

## Author

• A Full Stack Developer with 10+ years of experience in technical content creation.

• 