In: Computer Science
An Armstrong number is a number that is the sum of its own digits, each raised to the power of the number of its digits. For example, 153 is considered an Armstrong number because 13 + 53 + 33 = 153.
Write a VBA program that lists all 3-digit Armstrong numbers within a specified range of 3-digit positive integers. Your sub should do the following: 1) Using two input boxes, ask the user to input two 3-digit positive integers (a "lower bound" and an "upper bound" for the range); 2) Enter all Armstrong numbers between the specified numbers in column A, staring with cell A1. Hints: Use a For Loop. Also, string functions can be used on LONG variables.
VBA Code:
Function generateArmstringNumber()
'variable for upperbound lowerbound
Dim upperBound, lowerBound As Integer
Dim armStrongNumbers As New Collection 'to store the list of
armstrong numbers
'getting the data from the user
lowerBound = CInt(InputBox("Enter lower bound(3- Digit
Number)"))
upperBound = CInt(InputBox("Enter upper bound(3- Digit
Number)"))
'declaring program variables
Dim i As Integer
Dim itemp As Integer
Dim units, tens, hundreds As Integer
Dim sumOfDigits As Integer
'looping from lowerbound to upperbound
For i = lowerBound To upperBound
itemp = i 'taking a temporary value of i
'getting each digit
units = itemp Mod 10
itemp = itemp \ 10
tens = itemp Mod 10
itemp = itemp \ 10
hundreds = itemp Mod 10
'calculating sum of digits
sumOfDigits = units ^ 3 + tens ^ 3 + hundreds ^ 3
'checking if sum of digits equals i
If sumOfDigits = i Then
armStrongNumbers.Add (i) 'if so adding to the list
End If
Next i
Sheets("Sheet1").Cells.Clear 'clearing existing data
'displaying the list in the column 1
For i = 1 To armStrongNumbers.Count
Cells(i, 1) = armStrongNumbers.Item(i)
Next i
End Function
Sample Output:
153 |
370 |
371 |
407 |
lowerbound = 100
upperbound = 999