Here, we will figure out how to check whether a given number is an Armstrong number or not utilizing class and objects (object-situated methodology)?
Armstrong Number – An Armstrong Number is a number which is equivalent to its the entirety of digit’s block. For instance – 153 is an Armstrong number: here 153 = (111) + (555) + (333).
This program will take a number and check whether it is Armstrong Number or Not.
Steps for checking Armstrong number:
Ascertain entirety of every digit’s 3D shape of a number.
Contrast that number and the resultant entirety.
On the off chance that Number and Sum of digit’s block are equivalent, at that point it is an Armstrong Number generally not.
We are executing this program utilizing the idea of classes and objects.
Initially, we make the Class with “Check” name with 1 quality (number) and 2 methods, the methods are:
- Constructor Method: This is made utilizing init inbuilt watchword. The constructor method is utilized to instate the traits of the class at the hour of object creation.
- Object Method: isArmstrong() is the object method, for making object method we need to go at any rate one parameter for example self watchword at the hour of capacity creation. This Object method has no utilization in this program.
Besides, we need to make an object of this class utilizing a class name with bracket then we need to call its method for our yield.
The following is the execution of the program,
Python code to check a number of objects made:
# Define a class for Checking Armstrong number class Check : # Constructor def __init__(self,number) : self.num = number # define a method for checking number is Armstrong or not def isArmstrong(self) : # copy num attribute to the temp variable temp = self.num res = 0 # run the loop untill temp is not equal to zero while(temp != 0) : rem = temp % 10 res += rem ** 3 # integer division temp //= 10 # check result equal to the num attribute or not if self.num == res : print(self.num,"is Armstrong") else : print(self.num,"is not Armstrong") # Driver code if __name__ == "__main__" : # input number num = 153 # make an object of Check class check_Armstrong = Check(num) # check_Armstrong object's method call check_Armstrong.isArmstrong() num = 127 check_Armstrong = Check(num) check_Armstrong.isArmstrong()
153 is Armstrong 127 is not Armstrong