Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to check a given number is armstrong or not

C++ Code Example — Loop Programs

ADVERTISEMENT

WAP to check a given number is armstrong or not

Objective

Write a C++ program to check if a given number is an Armstrong number.

Algorithm / Approach

  1. Read n and make a temporary copy.
  2. Use a while loop to count the total number of digits.
  3. Reset the temporary copy to n.
  4. In a second while loop, extract each digit (rem = temp % 10).
  5. Raise that digit to the power of the total digit count: p = pow(rem, digits).
  6. Add p to a running sum.
  7. Check if the calculated sum exactly equals the original number n.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
int main() {
 int n, temp, rem, p;
 int sum =0, digits =0;
 cout<<"Enter a Number : ";
 cin>>n;
 temp = n;
 while(temp !=0) {
  digits++;
  temp = temp/10;
 }
 temp = n;
 while(temp!=0) {
  rem = temp%10;
  p = pow(rem,digits);
  sum = sum+p;
  temp = temp/10;
 }
 if(n==sum)
  cout<< n<<" is armstrong no.";
 else
  cout<< n<<" is not armstrong no.";
return 0;
}

Expected Output

Enter a Number : 123
123 is not armstrong no.

Explanation of the Program

  • An Armstrong number (or Narcissistic number) is a number that is equal to the sum of its own digits, each raised to the power of the number of digits.
  • For example, 153 has 3 digits. (1³ + 5³ + 3³) = (1 + 125 + 27) = 153. Because it matches, 153 is an Armstrong number.

Complexity

Time Complexity O(log₁₀ n)
Space Complexity O(1)
ADVERTISEMENT