C Program to print Armstrong numbers from 100 to 500.
Objective
Write a C program to print all Armstrong numbers between 100 and 500.
Algorithm / Approach
- Start an outer
forloop fromi = 100to500. - Inside this loop, set
temp = iandsum = 0. - Start an inner
while(temp != 0)loop. - Extract the digit (
r = temp % 10) and add its cube to the sum (sum = sum + (r * r * r)). - After the inner loop, if
sum == i, printi.
main.c
#include<stdio.h>
int main() {
int i,r,sum,temp;
for(i=100;i < = 500;i++) {
temp = i;
sum = 0;
while(temp!=0) {
r = temp%10;
temp = temp/10;
sum = sum+(r*r*r);
}
if(sum==i)
printf("%d ",i);
}
return 0;
}
Expected Output
153 370 371 407
Explanation of the Program
- This program uses Nested Loops. The outer
forloop generates the range of numbers to test. - The inner
whileloop performs the actual Armstrong logic on each individual number. Because all numbers between 100 and 500 have exactly 3 digits, we can hardcode the exponent as 3 (r*r*r) rather than counting the digits dynamically.
Complexity
Time Complexity
O(n) - Where n is the range (400 iterations), each having a constant 3 inner loop iterations.
Space Complexity
O(1)