Q:

Write C# program find Armstrong numbers between 1 to n

0

Write C# program find Armstrong numbers between 1 to n

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.

What is Armstrong number?

An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.

For Example: 407 = 43 + 03 + 73 = 64 + 0 + 343 = 407

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
public class csharpExercise
{
    static void Main(string[] args)
    {
        int lower, higher, i, temp1, temp2, remainder, n = 0;
        double result = 0;
 
        // Reading number
        Console.Write("Please Enter two numbers: ");
        lower = Convert.ToInt32(Console.ReadLine());
        higher = Convert.ToInt32(Console.ReadLine());
 
        Console.Write("Armstrong numbers between " + lower + " and " +  higher + " are: ");
 
        for (i = lower + 1; i < higher; ++i)
        {
            temp2 = i;
            temp1 = i;
 
            // number of digits calculation
            while (temp1 != 0)
            {
                temp1 /= 10;
                ++n;
            }
 
            // result contains sum of nth power of its digits
            while (temp2 != 0)
            {
                remainder = temp2 % 10;
                result += Math.Pow(remainder, n);
                temp2 /= 10;
            }
 
            // checking if number i is equal to the sum of nth power of its digits
            if (result == i)
            {
               Console.WriteLine(i);
            }
 
            // resetting the values to check Armstrong number for next iteration
            n = 0;
            result = 0;
 
        }
 
        Console.ReadLine();
    }
}

Result:

Please Enter two numbers: 200

500

Armstrong numbers between 200 and 500 are: 370

371

407

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now