Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print Armstrong number from 100 to 500

C++ Code Example — Series Programs

ADVERTISEMENT

WAP to print Armstrong number from 100 to 500

Objective

Write a C++ program to print all Armstrong numbers between 100 and 500.

Algorithm / Approach

  1. Start a for loop with i from 100 to 500.
  2. Inside the loop, set temp = i and sum = 0.
  3. Use a while(temp != 0) loop to extract digits: r = temp % 10.
  4. Calculate the cube of the digit and add to sum: sum = sum + (r * r * r).
  5. Divide temp by 10.
  6. After the while loop, if sum == i, print i.
main.cpp
#include<iostream>
using namespace std;
int main() {
 int i, r, temp, sum =0;
 for(i=100; i<=500; i++) {
  temp = i;
  sum = 0;
  while(temp!=0) {
   r = temp%10;
   sum = sum+(r*r*r);
   temp = temp/10;
  }
  if(sum ==i) {
   cout<< i<<"  ";
  }
 }
cout<< endl;
return 0;
}

Expected Output

153  370  371  407

Explanation of the Program

  • Instead of checking a single user-input number, we use an outer for loop to iterate through a specific range of numbers (100 to 500).
  • Because we know all numbers in this specific range are 3 digits long, we don't need to dynamically calculate the power for the Armstrong formula; we can safely hardcode the digit cubing (r * r * r).

Complexity

Time Complexity O(n) - Where n is the range of numbers checked.
Space Complexity O(1)
ADVERTISEMENT