In this example, you will learn to check whether an integer entered by the user is an Armstrong number or not.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
static void Main(string[] args) { int num, originalNum, remainder, n = 0; double result = 0; Console.Write("Enter an integer: "); num = Convert.ToInt32(Console.ReadLine()); originalNum = num; // store the number of digits of num in n for (originalNum = num; originalNum != 0; ++n) { originalNum /= 10; } for (originalNum = num; originalNum != 0; originalNum /= 10) { remainder = originalNum % 10; // store the sum of the power of individual digits in result result += Math.Pow(remainder, n); } // if num is equal to result, the number is an Armstrong number if ((int)result == num) Console.WriteLine("{0} is an Armstrong number.", num); else Console.WriteLine("{0} is not an Armstrong number.", num); Console.ReadKey(); } |