Write a program using FOR Loop to reverse the digits of the number. Write a c program to reverse a number using For Loop. Ex. if you enter 123456789 then the reverse number will be 987654321. All of you know better how to reverse a given number! Reversed number is a number written by reversing the order of digits. The first digit becomes the last and vice versa.
Read: Reverse a Number in C++
C Program to Reverse a Number Using FOR Loop
#include<stdio.h>
int main() {
/*C Program to Reverse a Number Using FOR Loop*/
int number, reminder, reverse = 0;
printf("Enter Any Number to be Reversed :\n");
scanf("%d", & number);
for (; number != 0; number = number / 10) {
reminder = number % 10;
reverse = reverse * 10 + reminder;
}
printf("\nReverse a Number is : %d", reverse);
return (0);
}
C Program to Reverse a Number Using While Loop
#include<stdio.h>
int main() {
/*C Program to Reverse a Number Using WHILE Loop*/
int number, reminder, reverse = 0;
printf("Enter Any Number to be Reversed :\n");
scanf("%d", & number);
while (number >= 1) {
reminder = number % 10;
reverse = reverse * 10 + reminder;
number = number / 10;
}
printf("\nReverse a Number is : %d", reverse);
return (0);
}
The Logic of Reverse a Number
Let's take an example to understand How to Reverse a Number in C. The logic for reversing a digit is very simple. Let's understand by taking an example 12345. Now divide a number by 10, so we get the remainder of 5. Store the remainder in the variable and then and using this logic we multiply Reverse = Reverse * 10 + Remainder, again divide the number by 10, now the number is 1234 and repeat the process again and again until the number becomes greater or equal to 1.
How to Reverse a Number in C
Here are the five steps to Reverse a Number in C Programming Language.
- First, take a number and store it in the variable.
- Now divide the number by 10 and store the remainder in another variable.
- Take a third variable and multiply by 10 and add the remainder.
- Again divide the number by 10, Now the number is divisible by 10 Until the Number becomes greater or equal by 1.
- Repeat the process again and again.
The Output of C Program to Reverse a Number
All C Programs for Practice PDF Free with solutions in single care but before that, We are Welcoming you to the c programs practice and solution page.
0 Comments: