## Tuesday, September 1, 2015

### C Programs on flow control statements (if, switch, loop, break and continue)-7

2015 & 2016 Batch Freshers Registration Link

JOIN MY FACEBOOK GROUP FOR UPDATES

C program to Check Armstrong Number
Armstrong number c program: c programming code to check whether a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208 etc. Read more about Armstrong numbers at Wikipedia. We will consider base 10 numbers in our program. Algorithm to check Armstrong is: First we calculate number of digits in our program and then compute sum of individual digits raise to the power number of digits. If this sum equals input number then number is Armstrong otherwise not an Armstrong number.
Examples:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096).
1741725 = 1^7 + 7^7 + 4^7 + 1^7 + 7^7 + 2^7 +5^7 (1 + 823543 + 16384 + 1 + 823543 +128 + 78125)
int power(int, int);
int main()
{
int n, sum = 0, temp, remainder, digits = 0;
printf("Input an integer\n");
scanf("%d", &n);

temp = n;
// Count number of digits
while (temp != 0)
{
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0)
{
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
printf("%d is an Armstrong number.\n", n);
else
printf("%d is not an Armstrong number.\n", n);
}

int power(int n, int r)
{
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Write a c program to check given number is strong number or not.
Definition of strong number:

A number is called strong number if sum of the factorial of its digit is equal to number itself. For example: 145 since
1! + 4! + 5! = 1 + 24 + 120 = 145

Algorithm:
1. Extracting digit from a given number
2. Finding factorial of the extracted digit

#include<stdio.h>
main()
{
int num,i,f,r,sum=0,temp;

printf("Enter a number: ");
scanf("%d",&num);

temp=num;
while(num)
{
i=1,f=1;
r=num%10;  /* Extracting digit */

while(i<=r)   /* finding factorial  */
{
f=f*i;
i++;
}
sum=sum+f;
num=num/10;
}
if(sum==temp)
printf("%d is a strong number",temp);
else
printf("%d is not a strong number",temp);
}

Sample output:
Enter a number: 145
145 is a strong number

Name

Email *

Message *