C Programming

Solved Example

Practice Questions

Exercise Question

Generate all Armstrong numbers between 1 to 500

Objective

Write a program to all Armstrong numbers between 1 to 500. If the sum of the cubes of each digit of the number is equal to the number itself, then the number is called Armstrong number. For example: 153 = (1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3)

Problem / Solution

#include<stdio.h>
int main() {
	int n;
	int dig,old,arm;
	
	for(n = 1; n <= 500; n++) {
		old = n; //store number into temp variable
		arm = 0;
		while(n != 0) {
			dig = n % 10;
			arm = arm + dig * dig * dig;
			n = n / 10;
		}
		
		if(old == arm) {
			printf("%d\t",old);
		}	
		
		n = old; //restore number from temp
	}
}

Sample Output

1       153     370     371     407