Write C# program find Armstrong numbers between 1 to n


Introduction

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


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public class csharpExercise
  7. {
  8. static void Main(string[] args)
  9. {
  10. int lower, higher, i, temp1, temp2, remainder, n = 0;
  11. double result = 0;
  12.  
  13. // Reading number
  14. Console.Write("Please Enter two numbers: ");
  15. lower = Convert.ToInt32(Console.ReadLine());
  16. higher = Convert.ToInt32(Console.ReadLine());
  17.  
  18. Console.Write("Armstrong numbers between " + lower + " and " + higher + " are: ");
  19.  
  20. for (i = lower + 1; i < higher; ++i)
  21. {
  22. temp2 = i;
  23. temp1 = i;
  24.  
  25. // number of digits calculation
  26. while (temp1 != 0)
  27. {
  28. temp1 /= 10;
  29. ++n;
  30. }
  31.  
  32. // result contains sum of nth power of its digits
  33. while (temp2 != 0)
  34. {
  35. remainder = temp2 % 10;
  36. result += Math.Pow(remainder, n);
  37. temp2 /= 10;
  38. }
  39.  
  40. // checking if number i is equal to the sum of nth power of its digits
  41. if (result == i)
  42. {
  43. Console.WriteLine(i);
  44. }
  45.  
  46. // resetting the values to check Armstrong number for next iteration
  47. n = 0;
  48. result = 0;
  49.  
  50. }
  51.  
  52. Console.ReadLine();
  53. }
  54. }

Result

C# language techstudy

     





Related Topics




Popular Posts