ISC COMPUTER SCIENCE THEORY PAPER JAVA PROGRAMS -2019 Question 7
Design a class ArmNum to check if
a given number is an Armstrong number or not.
[A number is said to be Armstrong
if sum of its digits raised to the power of length of the
number is equal to the number]
Example : 371 = 3^3 + 7^3 +
1^3
1634
= 1^44 + 6^4 + 3^4 + 4^4
54748 = 5^5 + 4^5 + 7^5 + 4^5 + 8^5
Thus 371, 1634 and 54748 are all
examples of Armstrong numbers.
Some of the members of the class
are given below:
Class name : ArmNum
Data members/instance variables: n : to store the number
l
: to store the length of the number
Methods/Member functions:
ArmNum (int nn): parameterized
constructor to initialize the data
member
n=nn
int sum_pow(int i): returns the sum of each digit raised to
the
power
of the length of the number using
recursive
technique
eg.
34 will return 3^2 + 4^2 (as the length of the
number
is 2)
void isArmstrong( ): checks whether
the given number is an
Armstrong
number by invoking the function
sum_pow(
) and displays the result with an
appropriate
message
Specify the class ArmNum giving
details of the constructor( ), int sum_pow(int) and void
isArmstrong( ).
Define a main( ) function to
create an object and call the functions accordingly to enable the task.
import java.util.*;
public class ISC2019Q7 {
public static void main(String[] args) {
int m,n;
Scanner in = new
Scanner(System.in);
do {
System.out.println("INPUT: Enter the value n:");
n= in.nextInt();
if(n <= 0)
System.out.println("Wrong input, please try again:");
}while (n <= 0);
ArmNum obj = new ArmNum(n);
obj.isArmstrong();
in.close();
}
}
class ArmNum {
public
void isArmstrong() {
if (nn ==
sum_pow(nn))
System.out.println(nn+" is an Armstrong Number");
else
System.out.println(nn+" is not an Armstrong Number");
}
public
int sum_pow(int i) {
if ( i <= 0)
return
sum_power;
else
return
(sum_power+(int)Math.pow(i%10, l)+sum_pow(i/10)); // using
recursion
}
private
void lengthofNumber() { //
calculates the length of the number
int temp=nn;
do {
temp /=10;
l++;
}while(temp > 0);
}
ArmNum(
int nn){
this.nn = nn;
l=0;
sum_power=
0;
lengthofNumber();
}
private
int nn;
private
int l;
private
int sum_power;
}
No comments:
Post a Comment