This blog is under construction

Saturday 22 June 2013

C program to print first N prime numbers

Write a C program to print first N prime numbers.



  #include <stdio.h>
  int main() {
        int n, i, flag = 1, num = 0, data = 2;
        printf("No of entries u need:");
        scanf("%d", &n);

        /* prime no is greater than 1 and it is divisible by 1 and itself */
        while (num < n) {
                for (i = 2; i <= data - 1; i++) {
                        if (data % i == 0) {
                                flag = 0;
                                break;
                        }
                }

                /* print prime numbers alone */
                if (flag) {
                        printf("%d ", data);
                        num++;
                }

                data++;
                flag = 1;
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  No of entries u need:20
  2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 



1 comment: