Tuesday 27 October 2015

Java program for armstrong number using recursion

An armstrong number is onw whose sum of the cube of digits is the number itself.
Example #1: 153 ; 13 + 53 + 33 = 1+ 125 + 27 = 153 (Hence Armstrong)
Example #2: 370 ; 33 + 73 + 03 = 27 + 343 + 0 = 370 (Hence Armstrong)
// Java program for armstrong number using recursion;
import java.util.*;
class armstrong
{
public static void main(String args[])
{
armstrong obj= new armstrong();
int i,n,sum,m;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
n=sc.nextInt(); // To read a number from the user.
m=obj.checknum(n); // The sum of cubes of digit will be stored in variable m.
if(n==m) // If sum of the cubes of a number(m) equals the number itself then it is a armstrong number.
System.out.println("It is a armstrong number");
else
System.out.println("Not a armstrong number");
}
 
int checknum(int n) // This function will return the sum of the cubes of the digits of a number
{
if(n==0)
return 0;
else
return (int)Math.pow(n%10,3)+ checknum(n/10);
}
}

1 comment:

  1. Armstrong Program in Java

    In general, Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits is equal to the number itself.
    Simple example of armstrong number is 153, 1 ^ 3 + 5 ^ 3 + 3 ^ 3 = 153

    ReplyDelete