Checking for Armstrong Number (3 Digit)
Program takes integer input and finds if given number is an armstrong number
Learning Objectives
This code helps to learn a common approach of processing an integer number digit by digit starting from its least significant digit.
Program Approach
Armstrong numbers are numbers where the sum of individual digits powered by count of total digits in the number is same as the number itself. Here we shall proceed to solve this by first reserving the copy of number in another number and then work on the copy of number by extracting each number from the last one by one and then the last number is powered by three as we are trying to find the armstrong number of a three digit number.
Source Code
|
|
Run Output
Code Understanding
First few lines of code should be clear if initial exercises of c++ has been done by the user.
int n1,rem, num=0;
n1 and rem variables are being declared here. the variable num is declared and initialized to 0 as it needs some first value before it is used in the loop.
n1=n;
make copy so that original number can later be compared to the result of loop
while(n1!=0)
The loop runs till all the digits of number have been exhausted and number just becomes 0.
rem=n1%10;
Remainder finding is done by dividing by 10 using the % (mod) operator which is meant to find the remainder of division.
num+=rem*rem*rem;
Since we are doing it for a three digit number we will simply multiply the number thrice to find the cube of a particular digit extracted as the remainder. if the number is 407, In first iteration of while loop remainder will be 7 and num will become 343 which is 7x7x7 .
n1/=10;
This can also be written as n1=n1/10. A number divided by 10 in integer form will actually remove the last digit of number. If number is 407 then 407/10 will be 40 as only integer portion of 40.7 will be taken.
if(n==num)
Since we kept the value of n intact, we can now use it to compare it with the resulting number prepared in the variable num. If it matches, the given number is an armstrong number.
Notes
Test case of 153, 370, 371 etc. shall be tried. surf the net to find more armstrong numbers.
Suggested Filename(s): checkarmstrong.cpp, armstrong.cpp, armstrong3.cpp
Created: 1-Dec-2017 20:51 | Updated: 15-Sep-2018 13:48|
