Write C program to print perfect numbers between given interval 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 program to print perfect numbers between given interval using function


  1. #include <stdio.h>
  2.  
  3. // Function declarations
  4. int isPerfect(int num);
  5. void printPerfect(int start, int end);
  6.  
  7.  
  8.  
  9. int main()
  10. {
  11. int start, end;
  12.  
  13. // Inputting lower and upper limit to print perfect numbers
  14. printf("Enter lower limit to print perfect numbers: ");
  15. scanf("%d", &start);
  16. printf("Enter upper limit to print perfect numbers: ");
  17. scanf("%d", &end);
  18.  
  19. printf("All perfect numbers between %d to %d are: \n", start, end);
  20. printPerfect(start, end);
  21.  
  22. return 0;
  23. }
  24.  
  25. int isPerfect(int num)
  26. {
  27. int i, sum;
  28.  
  29. // Finding sum of all proper divisors
  30. sum = 0;
  31. for(i=1; i<num; i++)
  32. {
  33. if(num % i == 0)
  34. {
  35. sum += i;
  36. }
  37. }
  38.  
  39. /*
  40.   If sum of proper positive divisors equals to given number
  41.   then the number is perfect number
  42.   */
  43. if(sum == num)
  44. return 1;
  45. else
  46. return 0;
  47. }
  48.  
  49. //Printing all perfect numbers
  50. void printPerfect(int start, int end)
  51. {
  52. // Iterating from start to end
  53. while(start <= end)
  54. {
  55. if(isPerfect(start))
  56. {
  57. printf("%d ", start);
  58. }
  59.  
  60. start++;
  61. }
  62. }
  63.  

Result

C language

     





Related Topics




Popular Posts