Home » .Net

Define Armstrong numbers and write program to check given number is Armstrong or not, in C#

Learn: What are the Armstrong numbers, how to check whether a number is Armstrong or not, In this program we are going to implement a program in C#, that will check the Armstrong number?

To understand the program of Armstrong numbers, first we should understand the concept of Armstrong numbers.

An Armstrong number is a number which is the sum of, power of each digit by total number of digits.

For example:

153 is an Armstrong number: 13 + 53 +33 = 153

Consider the program:

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

namespace ConsoleApplication1
{
    
    class Program
    {
        static void Main(string[] args)
        {
            int i         = 0;
            int digiCount = 0;
            int number    = 0;
            int tNumber    = 0;
            int []digiArray = new int[10];
            double sum = 0;

            Console.Write("Enter Number : ");
            tNumber = number = int.Parse(Console.ReadLine());

            //To find out total number of digits in number
            while (number > 0)
            {
                digiArray[i++] = number %10; 
                number = number / 10;
                digiCount++;
            }

            for(i=0;i<digiCount;i++)
            {
                sum += Math.Pow(digiArray[i], digiCount);
            }

            if (sum == tNumber)
                Console.WriteLine("Given Number is armstrong");
            else
                Console.WriteLine("Given Number is not armstrong");
        }
    }
}

Output

Enter Number : 153
Given Number is armstrong

In above program, first of all we are finding total number of digits in given number, and store each digit into an array then using power method of Math class, find power then calculate sum of each result, then comparing sum and number, if it is equal then it is Armstrong otherwise it is not Armstrong.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.