Python program to check Armstrong number using object oriented approach

Here, we are going to learn how to check whether a given number is an Armstrong number or not using class & objects (object-oriented approach)? Submitted by Ankit Rai Last updated : September 17, 2023

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.

Algorithm/Steps

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.

Program implementation

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 Method: isArmstrong() 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.

Below is the implementation of the program,

Python program to check Armstrong number using object oriented approach

# 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

The output of the above program is:

153 is Armstrong
127 is not Armstrong

Python class & object programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.