beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C++ Program to check Armstrong Number

By Chaitanya Singh | Filed Under: C++ Programs

An integer number is called Armstrong number if sum of the cubes of its digits is equal to the number itself. For example:
370 is an armstrong number because:

370 = 3*3*3 + 7*7*7 + 0*0*0
    = 27 + 343 + 0
    = 370

Example: Check Armstrong Number using For loop

To understand this program, you should have the knowledge of for loop and if-else statement.

#include <iostream>
using namespace std;

int main() {
   int num, sum = 0, digit;
   cout<<"Enter a positive integer: ";
   cin>>num;

   for(int temp=num; temp!=0;){
      digit = temp % 10;
      sum = sum +(digit * digit * digit);
      temp = temp/10;
   }

   if(sum == num)
      cout<<num<<" is an Armstrong number.";
   else
      cout<<num<<" is not an Armstrong number.";

   return 0;
}

Output:

Enter a positive  integer: 370
370 is an Armstrong number.

You can also use while loop instead of for loop to check the Armstrong number:
Replace this part of the code:

for(int temp=num; temp!=0;){
    digit = temp % 10;
    sum = sum +(digit * digit * digit);
    temp = temp/10;
}

with this:

int temp = num;
while(temp != 0)
{
   digit = temp % 10;
   sum = sum +(digit * digit * digit);
   temp = temp/10;
}

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap