Q20. Write a code to check armstrong number
Armstrong Number :- A Armstrong Number is a number that is equal to sum of cubes of each digits.
For Example :- 370
So as we can see that the sum of cubes of each digit (3^3=27, 7^3=343, 0^3=0 => 27+343+0=370) is equal to it’s number. So 370 is an Armstrong number.
Algorithm for Armstrong Number
START
step 1 : read number
step 2 : set sum=0 and duplicate=number
step 3 : reminder=number%10
step 4 : sum=sum+(reminder*reminder*reminder)
step 5 : number=number/10
step 6 : repeat steps 4 to 6 until number > 0
step 7 : if sum = duplicate
step 8 : display number is armstrong
step 9 : else
step 10 : display number is not armstrong
STOP
Code for Armstrong Number
#include <stdio.h>
int main() {
int num=370, new_num, rem, res = 0;
new_num = num;
while (new_num != 0) {
rem = new_num % 10;
res += rem * rem * rem;
new_num /= 10;
}
if (res == num)
printf(“The number %d is an Armstrong number.”, num);
else
printf(“The number %d is not an Armstrong number.”, num);
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int N=370, num, rem, sum = 0;
num = N;
while(num != 0)
{
rem = num % 10;
sum += rem * rem * rem;
num /= 10;
}
if(sum == N)
cout <<“The number “<< N <<” is an Armstrong number.”;
else
cout <<“The number “<< N <<” is not an Armstrong number.”;
return 0;
}
public class LFC {
public static void main(String[] args) {
int num = 370, new_num, rem, res = 0;
new_num = num;
while (new_num != 0)
{
rem = new_num % 10;
res += Math.pow(rem, 3);
new_num /= 10;
}
if(res == num)
System.out.println(“The number “+num+” is an Armstrong number.”);
else
System.out.println(“The number “+num+” is not an Armstrong number.”);
}
}
num = 370
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(“The number {0} is Armstrong number”.format(num))
else:
print(“The number {0} is not Armstrong number”.format(num))
$num=370;
$total=0;
$x=$num;
while($x!=0)
{
$rem=$x%10;
$total=$total+$rem*$rem*$rem;
$x=$x/10;
}
if($num==$total)
{
echo “The number $num is Armstrong number”;
}
else
{
echo “The number $num is not an Armstrong number”;
}
Output
The number 370 is an Armstrong number.
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number