In this post, you will learn how to Check Armstrong Number using C++ programming language.
This lesson will teach you how to Check Armstrong Number, with a while loop, assignment operator and decision making statement using the C++ Language. Let’s look at the below source code.
How to Check Armstrong Number?
RUN CODE SNIPPETSource Code
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cin>>n;
cout<<"Enter the Number = "<<n<<endl;
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
cout<<"\n"<<temp<<" is a Armstrong Number."<<endl;
else
cout<<"\n"<<temp<<" is not a Armstrong Number."<<endl;
return 0;
} Input
370
Output
Enter the Number = 370 370 is a Armstrong Number.
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- An Armstrong number, also known as narcissistic number, is a number that is equal to the sum of the cubes of its own digits. For example, 370 is an Armstrong number since 370 = 3*3*3 + 7*7*7 + 0*0*0 .
- Declare the variables and strings n,r,sum,tempan integers and assign the value 0 to sum.
- Collect the number from the user and store it in n using function
cin>>and display the value usingcout<<and the Insertion Operators'<<‘ , ‘>>’. - Using the assignment operator assign
temp=nand create a while loop with the condition(n>0) - Create the loop statement with the following functions
r=n%10to find the reminder of n and 10 and store the value in r, perform the mathematical functionsum=sum+(r*r*r)and store the value in sum. n=n/10is the final function in the loop statement and the answer is stored in n.- The loop is executed multiple times until the condition is false and the loop is exited.
- Using the decision making if else statement with the condition
(temp==sum), display the respective output statement according to whether the condition is satisfied or not.
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.