Write C++ program to find Armstrong numbers between 1 to n


techstudy.org

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

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. int lower, higher, i, temp1, temp2, remainder, n = 0, result = 0;
  9.  
  10. //Reading two numbers from user
  11. cout<<"Enter two numbers: ";
  12. cin>>lower;
  13. cin>>higher;
  14.  
  15. cout<<"Armstrong numbers between "<< lower << " and "<<higher << " are: ";
  16. for(i = lower + 1; i < higher; ++i)
  17. {
  18. temp2 = i;
  19. temp1 = i;
  20.  
  21. // number of digits calculation
  22. while (temp1 != 0)
  23. {
  24. temp1 /= 10;
  25. ++n;
  26. }
  27.  
  28. // result contains sum of nth power of its digits
  29. while (temp2 != 0)
  30. {
  31. remainder = temp2 % 10;
  32. result += pow(remainder, n);
  33. temp2 /= 10;
  34. }
  35.  
  36. // checking if number i is equal to the sum of nth power of its digits
  37. if (result == i) {
  38. cout<<i<<endl;
  39. }
  40.  
  41. // resetting the values to check Armstrong number for next iteration
  42. n = 0;
  43. result = 0;
  44.  
  45. }
  46.  
  47. return 0;
  48. }
  49.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts