Titikhyu Dixit Titikhyu Dixit - 1 month ago 7
C Question

Write a program in C to print armstrong numbers from 1 to 10000

This is the program I wrote. I get a blank output when I execute it. Can't figure out what's wrong with it.

#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
s = n;
while (n > 0) {
a = n % 10;
b = b + a * a * a;
n = n / 10;
}
if (b == s)
printf("%d ", s);
}
}

Answer

As others have suggested Don't change n inside the for loop as your loop depends on the variable n. you have to set b back to 0 for each iteration.

Your program is not very much readable as others might not understand what does a,b,n and s mean. So, always use meaningful variable names like this: (see comments for more description)

#include<stdio.h>  

int main(void)      //correct signature for main function
{
    int digit;  //instead of a
    int sum=0;  //instead of b
    int number; //instead of n

    printf("The armstrong numbers are-");

    for(number = 1; number <= 10000; number++)
    { 
        int temporary = number; //temporary integer to store number value
        sum = 0;                //sum must be reset to 0 at the start of each iteration

        while(temporary > 0) 
        {
            digit = temporary % 10; 
            sum = sum + (digit * digit * digit); 
            temporary = temporary / 10;
        }

        if(sum == number)        //if sum obtained == number, print it! 
            printf("%d ",number); 
    } 

    return 0;
}

output:

The armstrong numbers are-1 153 370 371 407 
Comments