Home Programs How to check whether the number is an Armstrong number in C#

How to check whether the number is an Armstrong number in C#

An Armstrong number or a plus perfect number) in a given number base is a number that is the sum of its own digits each raised to the power of the number of digits.

An Armstrong number is a number that is equal to the sum of cubes of its digits.

Examples of these are  0, 1, 153, 370, 371 and 407

Lets look at 153 as an example

(1 * 1 * 1) = 1
(5 * 5 * 5) = 125
(3 * 3 * 3) = 27

Now add 1 + 125 + 27 = 153

Example

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int myNumber, r, sumNumber = 0, tempNumber;
            Console.Write("Enter the Number= ");
            myNumber = int.Parse(Console.ReadLine());
            tempNumber = myNumber;
            while (myNumber > 0)
            {
                r = myNumber % 10;
                sumNumber = sumNumber + (r * r * r);
                myNumber = myNumber / 10;
            }
            if (tempNumber == sumNumber)
                Console.Write("An Armstrong Number.");
            else
                Console.Write("Not an Armstrong Number.");

            Console.ReadLine();
        }
    }
}

 

Test runs of this are

Enter the Number= 153
An Armstrong Number.

Enter the Number= 154
Not an Armstrong Number.

You may also like