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
- Start a
forloop withifrom 100 to 500. - Inside the loop, set
temp = iandsum = 0. - Use a
while(temp != 0)loop to extract digits:r = temp % 10. - Calculate the cube of the digit and add to sum:
sum = sum + (r * r * r). - Divide
tempby 10. - After the
whileloop, ifsum == i, printi.
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
forloop 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)