The C code below extracts all prime numbers between 0 and 1000. This code is included for those who may be interested. A proper understanding of this code is certainly not required to understand the other parts of this tutorial.
NOTE: The code below may not display correctly due to the constraints of this online editor.
//This code prints the prime numbers between 0 and 1000 sequentially.
#include <stdio.h>
#define MAX 1000
#define NUMBERS_PER_LINE 10
int main()
{
//declare and initialize 3 integers
int i = 0;
int j = 0;
int k = 0;
int count = NUMBERS_PER_LINE;
//create integer array
int numbers[MAX];
//manually store prime numbers 1 and 2 in array elements 0 and 1.
numbers[0] = 1;
numbers[1] = 2;
//loop from 3 to MAX
for(i = 3; i < MAX; i++)
{
numbers[i - 1] = i; //initialize array starting with array element 2
//loop from 2 to i - 1
for(j = 2; j < i; j++)
{
//employ modulus operator to check prime number criteria
if(i % j == 0) //not prime
{
numbers[i - 1] = 0; //replace non prime with zero
//terminate for loop
break;
}
}
}
//loop from 0 to MAX
for(k = 0; k < MAX; k++)
{
//only print if the value is non-zero
if(numbers[k] != 0)
{
//format integer output with 3 leading digits and a trailing space
printf("%3d ", numbers[k]);
//employ modulus operator to enforce a maximum per line output of 10 integers
if(count % NUMBERS_PER_LINE == 0)
{
printf("\n"); //print 10 numbers per line
}
//increment the count variable
count++;
}
}
//return program control from "main" with a non-error return code
return 0;
}
The next page of this tutorial will display the prime numbers that this code generates.