Menu Close

Armstrong Number in csharp

In this article we will learn about Armstrong Number in csharp. An ARMSTRONG NUMBER is a number which is made up of N digits and which is equal to the sum of each digit raised to the Nth power. Please read the previous article of Factorial in C#.

For more details of C#, please visit official Microsoft link.

What is Armstrong Number?

An ARMSTRONG NUMBER is a number which is made up of N digits and which is equal to the sum of each digit raised to the Nth power.

Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers. Let’s try to understand why 153 is an Armstrong number.

153 = (1*1*1) + (5*5*5) + (3*3*3)
where:           
(1*1*1)=1
(5*5*5)=125
(3*3*3)=27
So the Final Output is:      
1+125+27=153
Armstrong number

Example in c#

using System;  
  public class ArmstrongExample  
   {  
     public static void Main(string[] args)  
      {  
       int  n,r,sum=0,temp;      
       Console.Write("Enter the Number= ");      
       n= int.Parse(Console.ReadLine());     
       temp=n;      
       while(n>0)      
       {      
        r=n%10;      
        sum=sum+(r*r*r);      
        n=n/10;      
       }      
       if(temp==sum)      
        Console.Write("Armstrong Number.");      
       else      
        Console.Write("Not Armstrong Number.");      
      }  
  }  

Code Explanation

1. We define four integer variable numbers, sum, rem and temp then assign zero (0) to the sum.

2. Then get user input by Console.ReadLine() and pass this input to the number variable by converting it to an integer.

3. Now assign this user input number to our temp variable for future use.

4. Then we iterate while look until the number became zero(0).

5. In loop:

First, we find the Remainder of the number by module its by 10.

Then we get the power of this remainder by simply multiply it three times and add in our sum variable.

Then assign the result of sum and power of remainder to the sum variable.

Last, we divide the number by 10.

6. After a loop, check if the temp variable and sum variable are equal. If both are equal, then it’s an Armstrong number, otherwise not.

7. Then we use the Console.ReadKey() method to read any key from the console. By entering this line of code, the program will wait and not exit immediately. The program will wait for the user to enter any key before finally exiting. If you don’t include this statement in the code, the program will exit as soon as it is run.

Output:

Enter the Number= 153
Armstrong Number.
Enter the Number= 342   
Not Armstrong Number.

Hope It will clear about the program of Armstrong Number in csharp . Still have any question regarding this please send your feedback.

Leave a Reply

Your email address will not be published.