In the C programming language, to reverse a number means to rearrange its digits so that the digit at the last position becomes the first, and vice versa. For example, the number 2543, its reverse would be 3452.
// Write a c program to reverse the number given by the user.
#include<stdio.h>
int main(){
int n, reverse = 0;
printf("Enter the number : ");
scanf("%d", &n);
while(n > 0){
int last_digit = n % 10; // get the last digit from the number.
reverse = (reverse * 10 ) + last_digit; // Store the last digits into the reverse integer variable.
n /= 10; // remove the last digit from the number.
}
printf("Reverse : %d", reverse);
return 0;
}
#include<stdio.h>
This line includes the library of the input/output operation, After includes this line we can used the printf() function and scanf() function.
int main(){
It is the main function of the program, which is also called as the entry point of any c program. Which means every programs start from the main() function.
int n, reverse = 0;
Declared the variable as integers names n and reverse = 0.
printf("Enter the number : ");
It is show the prompts to the user enter the number using printf().
scanf("%d", &n);
Reads the number from the user as integers and store the value in n variable, "%d" is the format specifier which indicates that can only store the integer value.
// while loop to reverse the number
while(n > 0){
int last_digit = n % 10;
reverse = (reverse * 10 ) + last_digit;
n /= 10;
}
Use the while loop and the execute the statement inside the loop while n > 0. The lines into the loop works int last_digit = n % 10; get the last digit from the number. reverse = (reverse * 10 ) + last_digit; Store the last digits into the reverse integer variable. n /= 10; remove the last digit from the number.
printf("Reverse : %d", reverse);
Displayed the reverse of the given number using printf() function.
return 0;
}
Successfully execute the program, and return 0..
// Pseudocode
1. INCLUDE stdio.h
2. FUNCTION main()
1. DECLARE and SEt n, reverse = 0 as integer
2. PRINT "Ente the number : "
3. READ n FROM USER
4. while (n > 0)
1. SET last_digit = n % 10
2. SET reverse = (reverse * 10) + last_digit
3. SET n/=10 OR n = n / 1
5. PRINT "Reverse : %d", reverse
6. RETURN 0
3. END
Comments
Oops!