Wednesday, July 30, 2014

Program to find the Armstrong Number

Consider a number 153. The number has three digits so it becomes the power of each digit. Example: 1^3 + 5^3 + 3^3 = 153. The resultant after calculation is equal to the number itself(Armstrong Number).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Apps
{
    class ArmstrongNumberM
    {
        //private int number;
        private int count = 0, tempnum = 0, armstrong = 0,i=0;
        private int[] digits = new int[5];
        public int CountDigits(int num)
        {

            // count digits
            tempnum = num;
            while (tempnum % 10 > 0)
            {
                digits[count] = tempnum % 10;
                tempnum = tempnum / 10;
                count++;
            }
            int s = Evaluator();
            return s;
        }
        public int Evaluator()   // Scope of this method is within countDigits() only so calling this method in it.
        {
            for (int i = 0; i < count; i++)
            {
                armstrong += (int)Math.Pow((double)digits[i], (double)count);
            }
            return armstrong;


        }
    }
    class ArmstrongNumber
    {
        public static void Main()
        {
            Console.WriteLine("Enter the Number to Check for Armstrong or not");
            ArmstrongNumberM s1 = new ArmstrongNumberM();
            //  Console.WriteLine(s1.CountDigits(Int32.Parse(Console.ReadLine())));        // Passing the input to count number of digits method
            int numberentered = int.Parse(Console.ReadLine());
            int returnvalue = s1.CountDigits(numberentered);
            if (numberentered == returnvalue)
            {
                Console.WriteLine("Entered number is Armstrong Number");
            }
            else
                Console.WriteLine("Entered number is NOT Armstrong Number");
        }
    }
}

No comments:

Post a Comment