Generating Prime Numbers – C

This blog we are going to see how do we generate prime numbers in C programming.

Let us looks at the parameters first and then go ahead with the coding part:

  1. Variables
  2. Inner and outer looping: for looping..
  3. Header files library: some include #stdio.h, #stdlib.h, #stdbool.h
  4. Prime Index: skips the even numbers.

Coding part:

/* basic skeleton of the code */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int main(){
/* variable initialization */
int p;
    int i;
    int prime[50] = {0};
    int primeIndex = 2; //skips the even numbers
    bool isPrime;
    
//hardcode
prime[0]= 1;
prime[1] = 3;
for(p=5;p<=100;p=p+2){ /*outer looping*/
    isPrime = true;
    for(i=1;i = p && i/prime[i]>=prime[i]; ++i) /* inner looping */
    if(p % prime[i] == 0) /* % used here because after the division of the i by primes what ever remainder we get is going to be zero..
    isPrime= false;
    
/*executing the true condition */
 if(prime[i] == true){
      prime[primeIndex] = p;
        ++primeIndex;
   }
}
/*output coding */ 
for(i=0;i<prime[i];++i)
    printf("%i ",prime[i]);
    printf("\n");
    return 0;
}
Full Code:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int main(){
    int p;
    int i;
    int prime[50] = {0};
    int primeIndex = 2; //skips the even numbers
    bool isPrime;
    
//harcode
prime[0]= 1;
prime[1] = 3;
for(p=5;p<=100;p=p+2){
    isPrime = true;
    for(i=1;i = p && i/prime[i]>=prime[i]; ++i)
    if(p % prime[i] == 0)
    isPrime= false;
    
    if(prime[i] == true){
        prime[primeIndex] = p;
        ++primeIndex;
    }
}
    for(i=0;i<prime[i];++i)
    printf("%i ",prime[i]);
    printf("\n");
    return 0;
}

Scroll to top