Program in C to reverse a given Number
Below is the C program to reverse a given number. This C program will accept a number (in a variable named “num”) and performs an operation to reverse the number.
#include <stdio.h> #include <stdlib.h> int main(void) { int num=1234, newNum=0; while(num!=0){ newNum=newNum*10 + num%10; num=num/10; } printf("\n"); printf("%d", newNum); return 1; }
Output: 4321
Explanation:
The statement while(num!=0) will be executed till value of num !=0
num%10 (read as num mod 10) will return the last digit. So in 1st iteration, it will return 4.
So, newNum will become–> 0*10 + 4 –>4
Next line i.e. num/10 will return 123
In the 2nd Iteration, newNum=4*10 + (num%10) –> 4*10 + 3 –> 43 and num = 123/10 = 12.
This loop continues until value of num becomes zero.
Click here for steps to set-up and install Eclipse for C Programming
It would be helpfull if every line’s function is explained.
The statement while(num!=0) will be executed till value of num !=0
num%10 (read as num mod 10) will return the last digit.
So in 1st iteration, it will return 4.
So newNum will become–> 0*10 + 4 –>4
next line i.e. num/10 will return 123
2nd Iteration:
newNum=4*10 + (num%10)–>4*10 + 3 –>43
num = 123/10 = 12
This loop continues until value of num becomes zero.
Hope its clear.
Ya !! This is an interesting website that i have ever searched
I like its tutorials very much..
#include
#include
#include
#include
void main()
{
int num1, num2;
char str[10];
clrscr();
printf(“\nEnte the Number : “);
scanf(“%d”,&num1);
sprintf(str,”%d”,num1);
strrev(str);
num2 = atoi(str);
printf(“\nReversed Number : “);
printf(“%d\n”,num2);
getch();
}
(i think itz btr)
what about the reverse of a string????
Good explanation for reverse the number
Thank you everyone for the wonderful comments. I hope this website is helping every one out there.
If you like this website, kindly share it with everyone.
Thanks,
LearnCOnline Team
while(num!=0){
rev=num%10;
num=num/10;
}
print rev and watch