write a program to read a number and find the sum of the individual digit, reverse and also Check whether it is a palindrome or not . it is a c language
Answers
Explanation:
Reverse an Integer
#include <stdio.h>
int main() {
int n, rev = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
rev = rev * 10 + remainder;
n /= 10;
}
printf("Reversed number = %d", rev);
return 0;
}
Output
Enter an integer: 2345
Reversed number = 5432
This program takes an integer input from the user. Then the while loop is used until n != 0 is false (0).
In each iteration of the loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times.
Inside the loop, the reversed number is computed using:
rev = rev*10 + remainder;
C program to execute the given task is as follows:
#include <stdio.h>
#include <math.h>
int getLength(int n) {
int copyOfn = n;
int l = 0;
while(copyOfn > 0) {
++l;
copyOfn /= 10;
}
return l;
}
int main() {
int n;
scanf("%d", &n);
int l = getLength(n);
int copyOfn = n;
int sumOfDigits = 0;
int revOfn = 0;
int d;
for(int i = (l -1); i >= 0; i--) {
d = copyOfn %10;
sumOfDigits += d;
revOfn += d * pow(10, i);
copyOfn /= 10;
}
printf("Sum of the digits = %d\n", sumOfDigits);
printf("Reverse of the no.= %d\n", revOfn);
if(n == revOfn)
printf("Palindrome number");
else
printf("Not a Palindrome number");
return 0;
}
- In the above code, first we read the number using scanf.
- Then we calculated the length of the number inputted by the user.
- Then we found the sum of the digits of the number and the reverse of it using for loop.
- Finally, we compared the number and the reverse of it, to check for palindrome and printed the data accordingly.
#SPJ3