Finding First N Prime Numbers Using C

CCBeginner
Practice Now

Introduction

In this lab, we will write a C program that will find the first n prime numbers using nested for loops. The value of n will be input by the user. We will iterate n times to find all the prime numbers.

Note: You need to create the file ~/project/main.c yourself to practice coding and learn how to compile and run it using gcc.

cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main

Include Libraries and Declare Variables

In the first step, we will include the necessary libraries. We will use only one library, stdio.h, which will be used for standard input and output. Then, we will declare the variables that we will use in our program.

#include <stdio.h>

int main()
{
  int n, i = 3, count, c;

Get Input

In the second step, we will get the number of prime numbers that we want to generate from the user. We will use the scanf function to get the input from the user.

printf("Enter the number of prime numbers required: ");
scanf("%d", &n);

Find Prime Numbers

In the third step, we will find the n prime numbers using nested for loops. The first prime number is 2, so we will print it outside of the loops. For finding the next prime numbers, we will iterate n times. In each iteration, we will check if the number i is prime or not. If it is prime, we will print it, and increase the count of prime numbers (count).

if (n >= 1) {
  printf("First %d prime numbers are: 2 ", n);
}

for (count = 2; count <= n;) {
  for (c = 2; c <= i - 1; c++) {
    if (i % c == 0) {
      break;
    }
  }
  if (c == i) {
    printf("%d ", i);
    count++;
  }
  i++;
}

Output the Result

In the fourth and final step, we will output the generated prime numbers to the console.

printf("\n");
return 0;

Summary

In this lab, we have learned how to find the first n prime numbers in C using nested for loops. We have gone through a step-by-step guide on how to create the program, including getting user input and iterating through different values to check if they are prime. Finally, we have outputted the results to the console.

Other C Tutorials you may like