Friday 24 April 2015

How to check a given number is Armstrong or not in c# asp.net ?

This is a very important question asked in interviews to check weather a given number is an Armstrong Number.
Here I am writing a program in c# to Check Whether the given number is an Armstrong number or Not .
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.

The condition for armstrong number is,
Sum of the cubes of its digits must equal to the number itself.

For example, 153 is given as input.
1 * 1 *1 + 5 * 5 * 5 + 3 * 3 * 3 = 153 is an armstrong number.

c# source code example for a given number:-

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

namespace ConsoleDemoApp
{
    class DemoTest
    {
        static void Main(string[] args)
        {
            int num, remain, sum = 0;
            Console.Write("Please enter a number:-");
            num = int.Parse(Console.ReadLine());
            for (int i = num; i > 0; i = i / 10)
            {
                remain = i % 10;
                sum = sum + remain * remain * remain;

            }
            if (sum == num)
            {
                Console.Write("{0} number is an Armstrong number", num);
            }
            else
            {
                Console.Write("{0} number is not an Armstrong number!", num);
            }
            Console.ReadLine();
        }
    }

}

 Output:-









Here is source code print the list of number between 100 and 999


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsloeDemoApp
{
    class TestArmstrong
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Armstrong Numbers between 100 - 999 are :-");

            for (int i = 100; i <= 999; i++)
            {
                int firstDigit = i / 100;
                int secondDigit = (i - firstDigit * 100) / 10;
                int thirdDigit = (i - firstDigit * 100 - secondDigit * 10);

                int d = firstDigit * firstDigit * firstDigit + secondDigit * secondDigit * secondDigit +
                    thirdDigit * thirdDigit * thirdDigit;

                if (i == d)
                    System.Console.WriteLine("{0}", i);
            }
            Console.ReadLine();
        }
    }


}

Output:-



No comments:

Post a Comment