C Programs Tutorials | IT Developer
IT Developer

Java Programs - Solved 2019 Theory Paper ISC Computer Science



Share with a Friend

Solved 2019 Theory Paper ISC Computer Science

Class 12 - ISC Computer Science Solved Theory Papers

Armstrong Number Program - ISC 2019 Theory

Design a class ArmNum to check if a given number is an Armstrong number or not. A number is said to be Armstrong if the sum of its digits raised to the power of length of the number is equal to the number.

Example:
371 = 33 + 73 + 13
1634 = 14 + 64 + 34 + 44
54748 = 55 + 45 + 75 + 45 + 85
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 num): parameterized constructor to initialize the data member n = num.
int sumPow(int i): returns the sum of each digit raised to the power of the length of the number using recursive technique. E.g. 34 will return 32 + 42 (as the length of the number is 2)
void isArmstrong(): checks whether the given number is an Armstrong number by invoking the function sumPow() and displays the result with an appropriate message.

Specify the class ArmNum giving details of the constructor, int sumPow(int) and void isArmstrong(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.io.*; class ArmNum{ private int n; private int l; public ArmNum(int num){ n = num; l = 0; for(int i = n; i != 0; i /= 10) l++; } public int sumPow(int i){ if(i < 10) return (int)Math.pow(i, l); return (int)Math.pow(i % 10, l) + sumPow(i / 10); } public void isArmstrong(){ if(n == sumPow(n)) System.out.println(n + " is an Armstrong number."); else System.out.println(n + " is not an Armstrong number."); } public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("N = "); int num = Integer.parseInt(br.readLine()); ArmNum obj = new ArmNum(num); obj.isArmstrong(); } }

Output

OUTPUT 1:
N = 371
371 is an Armstrong number.


OUTPUT 2:

N = 1634
1634 is an Armstrong number.

OUTPUT 3:

N = 54748
54748 is an Armstrong number.

OUTPUT 4:

N = 121
121 is not an Armstrong number.