ANY NUMBER :-no of digit,sum of digit,check for Armstrong number

 Armstrong :- a  number whose cubic sum of individual digit is equal to same number
package sum.of.digit;
import java.util.Scanner;
public class SumOfDigit {
void no_of_digit() {
Scanner sc = new Scanner(System.in);
System.out.println("enter number to know number of digit");
int no = sc.nextInt();
int nocount = 0;
while (no > 0) {
no = no / 10;
nocount++;
}
System.out.println("no of digit " + nocount);
}
/**documentation comment
*here nocount is initialized to count no of digit after each division by 10
* until number is greater than zero the while loop will continue
* at last when single digit left then further division will result decimal value(0.2 or 0.3) which is lees than zero so loop will fail
* and we will get the count of all digit till single digit left.
*/
void sum_of_digit() {
Scanner sc = new Scanner(System.in);
System.out.println("enter no to know sum of digit");
int no = sc.nextInt();
int sum = 0;
while (no > 0)
{
sum = sum + (no % 10);
no = no / 10;
}
System.out.println("the sum of digit is :" + sum);
}
/** documentation comment
* similarly here, we just add the remainder to sum box
*/
void armstrong_no_check() {
Scanner sc = new Scanner(System.in);
System.out.println("enter no to check for armstrong no");
int no = sc.nextInt();
int k = no;
int cubesum = 0;
int rem = 1;
while (no > 0)
{
rem = no % 10;
cubesum = cubesum + rem * rem * rem;
no = no / 10;
}
System.out.println("the cubesum of digit is :" + cubesum);
if (k == cubesum)
{
System.out.println("the entered number is an armstrong no");
}
else
{
System.out.println("the entered no is not an armstrong no");
}
}
/**documentation comment
* here instead of adding each digit to sum box, we add their cube of remainder to cubesum box
* finally we compare that with no
* caution we need to re-declear the no. at initial point because after while loop the number is no more the same no.
*/
public static void main(String[] args)
{
SumOfDigit ob = new SumOfDigit();
ob.no_of_digit();                                                //evaluating number of digit
ob.sum_of_digit();                                           //calculating sum of digit
ob.armstrong_no_check();                           //testing of armstrong no
}
}

                                    OUTPUT

enter number to know number of digit
153
no of digit 3
enter no to know sum of digit
153
the sum of digit is :9
enter no to check for armstrong no
153
the cubesum of digit is :153
the entered number is an armstrong no

No comments:

Post a Comment