C Program To Reverse a Number
C Program To Reverse a Number
Learn How To Reverse A Number in C Programming Language. It is important that we should know How A For Loop Works before getting further with this C Program Code.
To Reverse the Digits of an Integer, we need to Extract every End Digit using Modulus Operator and then store it in a Sum variable. Then, keep on adding the other digits to the Sum variable.
Example
Reverse of 1234 = 4321
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include<stdio.h>
#include<conio.h>
Void main()
{
int num, sum = 0, rem, temp;
printf("\nEnter a Number:\t");
scanf("%d", &num);
temp = num;
while(num > 0)
{
rem = num%10;
sum = (sum*10) + rem;
num = num/10;
}
printf("\nReverse of %d:\t%d\n", temp, sum);
}
|
Method 2: Reverse a Number using For Loop in C Programming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include<stdio.h>
#include<conio.h>
int main()
{
int num, sum = 0, rem, temp;
printf("\nEnter a Number:\t");
scanf("%d", &num);
for(temp = num; num > 0;)
{
rem = num%10;
sum = (sum*10) + rem;
num = num/10;
}
printf("\nReverse of %d:\t%d\n", temp, sum);
return 0;
}
|
Method 3: C Program Code To Reverse a Number using Function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#include<stdio.h>
int reverse(int x);
int main()
{
int num, res;
printf("\nEnter a Number:");
scanf("%d", &num);
res = reverse(num);
printf("\nReverse of %d is:%d\n", num, res);
return 0;
}
int reverse(int x)
{
int r, s = 0;
while(x > 0)
{
r = x%10;
s = (s*10) + r;
x = x/10;
}
return s;
}
|
Output:
Enter a Number: 5432
Reverse of 5432 is: 2345
Comments
Post a Comment