Armstrong Number in C#

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Armstrong Number in C#

Before going to write the C# program to check whether the number is Armstrong or not, let's understand what is Armstrong number.

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 371 is an Armstrong number.

 
  1. 371 = (3*3*3)+(7*7*7)+(1*1*1)      
  2. where:      
  3. (3*3*3)=27      
  4. (7*7*7)=343      
  5. (1*1*1)=1      
  6. So:      
  7. 27+343+1=371      

Let's see the C# program to check Armstrong Number.

 
  1. using System;  
  2.   public class ArmstrongExample  
  3.    {  
  4.      public static void Main(string[] args)  
  5.       {  
  6.        int  n,r,sum=0,temp;      
  7.        Console.Write("Enter the Number= ");      
  8.        n= int.Parse(Console.ReadLine());     
  9.        temp=n;      
  10.        while(n>0)      
  11.        {      
  12.         r=n%10;      
  13.         sum=sum+(r*r*r);      
  14.         n=n/10;      
  15.        }      
  16.        if(temp==sum)      
  17.         Console.Write("Armstrong Number.");      
  18.        else      
  19.         Console.Write("Not Armstrong Number.");      
  20.       }  
  21.   }  

Output:

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