Q:

Python program to check Armstrong number using object oriented approach

belongs to collection: Python class & object programs

0

Armstrong Number - An Armstrong Number is a Number which is equal to it's sum of digit's cube. For example - 153 is an Armstrong number: here 153 = (1*1*1) + (5*5*5) + (3*3*3).

This program will take a number and check whether it is Armstrong Number or Not.

Steps for checking Armstrong number:

  1. Calculate sum of each digit's cube of a number.
  2. Compare that number with the resultant sum.
  3. If Number and Sum of digit's cube is equal then it is an Armstrong Number otherwise not.

We are implementing this program using the concept of classes and objects.

Firstly we create the Class with "Check" name with 1 attributes (number) and 2 methods, the methods are:

  1. Constructor Method: This is created using __init__ inbuilt keyword. The constructor method is used to initialize the attributes of the class at the time of object creation.
  2. Object MethodisArmstrong() is the object method, for creating object method we have to pass at least one parameter i.e. self keyword at the time of function creation. This Object method has no use in this program.

Secondly, we have to create an object of this class using a class name with parenthesis then we have to call its method for our output.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python code to count number of objects created

# 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()      

Output

153 is Armstrong
127 is not Armstrong

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to check Palindrome number using ob... >>
<< Python program to count number of objects created...