Write a C program to check whether a given number is Armstrong or not.
If sum of nth power of digits of a number equals itself, then it is an Armstrong number. Here, n represents the number of digits in a number.
Example:
153 = 1^3 + 5^3 + 3^3 =153
Here, power 3 represents the number of digits in the given input(153).
1634 = 1^4 + 6^4 + 3^4 + 4^4
Here, 4 represents the number of digits in the given input(1634).
If sum of nth power of digits of a number equals itself, then it is an Armstrong number. Here, n represents the number of digits in a number.
Example:
153 = 1^3 + 5^3 + 3^3 =153
Here, power 3 represents the number of digits in the given input(153).
1634 = 1^4 + 6^4 + 3^4 + 4^4
Here, 4 represents the number of digits in the given input(1634).
int main() {
int res = 0, data, mod, temp, digits = 0;
printf("Enter your data:");
scanf("%d", &data);
temp = data;
/* calculating no of digits in given input */
while (data > 0) {
mod = data % 10;
data = data / 10;
digits++;
}
data = temp;
/* sum of nth power of digits */
while (data > 0) {
mod = data % 10;
res = res + pow(mod, digits);
data = data / 10;
}
if (res == temp)
printf("Given number is an armstrong\n");
else
printf("Given number is not an armstrong number\n");
return 0;
}
Note:
gcc ex05.c -lm
lm - linking math library for pow() function.
Output:
jp@jp-VirtualBox:~/$ gcc ex05.c -lm
jp@jp-VirtualBox:~/$ ./a.out
Enter your data:1634
Given number is an armstrong
jp@jp-VirtualBox:~/$ ./a.out
Enter your data:1634
Given number is an armstrong
No comments:
Post a Comment