Write C program to find prime numbers in given range using functions


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 find prime numbers in given range using functions


  1. #include <stdio.h>
  2.  
  3. // Function declarations
  4. int isPrime(int num);
  5. void printPrimes(int lower, int upper);
  6.  
  7. int main()
  8. {
  9. int lower, upper;
  10.  
  11. printf("Enter the lower and upper limit to list primes: ");
  12. scanf("%d%d", &lower, &upper);
  13.  
  14. // Calling function to print all primes between the given range.
  15. printPrimes(lower, upper);
  16.  
  17. return 0;
  18. }
  19.  
  20.  
  21.  
  22. // Print all prime numbers between lower limit and upper limit.
  23.  
  24. void printPrimes(int lower, int upper)
  25. {
  26. printf("List of prime numbers between %d to %d are: ", lower, upper);
  27.  
  28. while(lower <= upper)
  29. {
  30. // Printing if current number is prime
  31. if(isPrime(lower))
  32. {
  33. printf("%d ", lower);
  34. }
  35.  
  36. lower++;
  37. }
  38. }
  39.  
  40. //Checking whether a number is prime or not
  41. int isPrime(int num)
  42. {
  43. int i;
  44.  
  45. for(i=2; i<=num/2; i++)
  46. {
  47. /*
  48.   If the number is divisible by any number
  49.   other than 1 and self then it is not prime
  50.   */
  51. if(num % i == 0)
  52. {
  53. return 0;
  54. }
  55. }
  56.  
  57. return 1;
  58. }
  59.  

Result

C language

     





Related Topics




Popular Posts