Write C to check prime and armstrong numbers using function


Introduction

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.


techstudy.org

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

Write C to check prime and armstrong numbers using function


  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. int checkPrimeNumber(int n);
  5. int checkArmstrongNumber(int n);
  6.  
  7. int main()
  8. {
  9. int num, flag;
  10.  
  11. printf("Enter a positive integer: ");
  12. scanf("%d", &num);
  13.  
  14. // Checking prime number
  15. flag = checkPrimeNumber(num);
  16. if (flag == 1)
  17. printf("%d is a prime number.\n", num);
  18. else
  19. printf("%d is not a prime number.\n", num);
  20.  
  21. // Checking Armstrong number
  22. flag = checkArmstrongNumber(num);
  23. if (flag == 1)
  24. printf("%d is an Armstrong number.", num);
  25. else
  26. printf("%d is not an Armstrong number.",num);
  27. return 0;
  28. }
  29.  
  30. //function to check prime number
  31. int checkPrimeNumber(int num)
  32. {
  33. int i, flag = 1;
  34.  
  35. for(i=2; i<=num/2; ++i)
  36. {
  37.  
  38. // condition for non-prime number
  39. if(num%i == 0)
  40. {
  41. flag = 0;
  42. break;
  43. }
  44. }
  45. return flag;
  46. }
  47.  
  48. //function to check Armstrong Number
  49. int checkArmstrongNumber(int number)
  50. {
  51. int originalNumber, remainder, result = 0, num = 0, flag;
  52.  
  53. originalNumber = number;
  54.  
  55. while (originalNumber != 0)
  56. {
  57. originalNumber /= 10;
  58. ++num;
  59. }
  60.  
  61. originalNumber = number;
  62.  
  63. while (originalNumber != 0)
  64. {
  65. remainder = originalNumber%10;
  66. result += pow(remainder, num);
  67. originalNumber /= 10;
  68. }
  69.  
  70. // condition for Armstrong number
  71. if(result == number)
  72. flag = 1;
  73. else
  74. flag = 0;
  75.  
  76. return flag;
  77. }
  78.  

Result

C language

     





Related Topics




Popular Posts