I was making a program to check whether a given number is an Armstrong number or not, but it is not working correctly. I had used two print statements to check how much of my code is working but they are showing value of count and total as 0. I don’t know what is going wrong here.
#include<stdio.h>
#include<math.h>
int main ()
{
//Program to check if a given number is Armstrong or not.
int num, count, remain, total = 0;
int onum = num;
printf ("Enter a number:\n");
scanf ("%d", &num);
while (onum != 0)
{
onum = onum / 10;
count++;
}
printf ("Value stored at count is %d\n", count);
onum = num;
for (int i = 0; i < count; i++)
{
remain = onum % 10;
total += pow (remain, count);
onum = onum / 10;
}
printf ("Value stored at Total is %d\n", total);
if (num == total)
{
printf ("The entered number is an Armstrong\n");
}
else
{
printf ("The entered number is not an Armstrong\n");
}
return 0;
}
>Solution :
The logic given for calculating armstrong number is wrong. Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
#include<stdio.h>
#include<math.h>
int main ()
{
//Program to check if a given number is Armstrong or not.
int num, count, remain, total = 0;
int onum = num;
printf ("Enter a number:\n");
scanf ("%d", &num);
while (onum != 0)
{
onum = onum / 10;
count++;
}
printf ("Value stored at count is %d\n", count);
onum = num;
for (int i = 0; i < count; i++)
{
remain = onum % 10;
total += pow (remain,3); // logic for armstrong sum of cubes
onum = onum / 10;
}
printf ("Value stored at Total is %d\n", total);
if (num == total)
{
printf ("The entered number is an Armstrong\n");
}
else
{
printf ("The entered number is not an Armstrong\n");
}
return 0;
}