Saturday, June 10, 2017

C# - check if a given number is an Armstrong Number

This article will demonstrate how to check a number is an Armstrong number in C#

Armstrong Number:
- Source Google

An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371


class Program
    {
        static void Main(string[] args)
        {
            #region Armstrong Number

            Console.WriteLine("Enter a Number");
            Int32 number = int.Parse(Console.ReadLine());
            Console.WriteLine(CheckArmstrongNumber(number));
            Console.ReadKey();

            #endregion
        }

#region Armstrong Number

        private static string CheckArmstrongNumber(int number)
        {
            string msg = string.Empty;
            int rem = 0;
            int num = 0;
            int orgno = number;

            #region For Loop
            // Follow reverse the number technique and add the cubes of each digits          

            for (int i = number; i > 0; i = i / 10)
            {
                rem = i % 10;
                num += rem * rem * rem;
            }

            #endregion

            #region SecondWAY

            while (number > 0)
            {
                rem = number % 10;
                num += rem * rem * rem;
                number = number / 10;
            }

            #endregion

            if (orgno == num)
            {
                msg = "Entered Number is Armstrong Number.";
            }
            else
            {
                msg = "Entered Number is  not Armstrong Number.";
            }
            return msg;
        }

        #endregion

}

Console Output:

Enter a Number
371
Entered Number is Armstrong Number.






No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...