Armstrong Number in Swift Programming Language


Example to check whether an integer (entered by the user) is an Armstrong number or not using while loop and if…else statement.


A positive integer is called an Armstrong number of order n if
abcd = a pow n + b pow n + c pow n .....so on to n pow n 
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:
153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3  ../// 153 is Armstrong number 

Example #1: Check Armstrong Number of three digits

func checkAmstrongNumber(num:Int) -> String {
    var sum = 0
    var tempNum = num
    var reminder = 0
    while tempNum != 0  {
        reminder = tempNum % 10
        sum = sum + reminder * reminder * reminder
        tempNum /= 10
        if sum > num {break}
    }
    if sum == num {
        return "Yes"
    }
    return "No"
}
let numAm = 153
let resultAm = checkAmstrongNumber(num:numAm)
print(resultAm)

Output





Example #2: Check Armstrong Number of n digits




func checkAmstrongNumber(num:Int) -> String {
    var sum = 0
    var tempNum = num
    var reminder = 0
    let digits = String(num).count
    while tempNum != 0  {
        reminder = tempNum % 10
        sum = sum + Int(pow(Double(reminder), Double(digits)))
        tempNum /= 10
        if sum > num {break}
    }
    if sum == num {
        return "Yes"
    }
    return "No"
}
let numAm = 1634
let resultAm = checkAmstrongNumber(num:numAm)
print(resultAm)

Output



In this program, the number of digits of an integer is calculated first and stored in n variable. And, the pow() function is used to compute the power of individual digits in each iteration of the while loop.

Subscribe me to get notifications about new stories from Swift and iOS Development.
Did you gain value by reading this article?you’d like to see content like this more often, Subscribe me 

Comments

Post a Comment

Popular posts from this blog