Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to print Armstrong numbers from 100 to 500.

C Code Example — Loop Programs

ADVERTISEMENT

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

  1. Start an outer for loop from i = 100 to 500.
  2. Inside this loop, set temp = i and sum = 0.
  3. Start an inner while(temp != 0) loop.
  4. Extract the digit (r = temp % 10) and add its cube to the sum (sum = sum + (r * r * r)).
  5. After the inner loop, if sum == i, print i.
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 for loop generates the range of numbers to test.
  • The inner while loop 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)
ADVERTISEMENT