2077 7

CSC115 ยท 2077 ยท 5 marks

Write a program to display first n prime numbers.

Write a program to display first n prime numbers. [5]

C ProgrammingChapter 5: Control StatementDecision Making and Looping

Quick answer

A prime number is a number greater than 1 that has no divisors other than 1 and itself. To display the first N prime numbers, we use a nested loop: - The outer loop counts how many primes have been found so far. - The inner loop checks whether each candidate number is prime.

Program to Display First N Prime Numbers

Concept


Program

#include<stdio.h>
#include<conio.h>

void main()
{
    int n, num, i, count, primeCount;

    clrscr();

    printf("Enter how many prime numbers to display: ");
    scanf("%d", &n);

    printf("First %d prime numbers are:\n", n);

    primeCount = 0;   /* counts how many primes found so far */
    num = 2;          /* start checking from 2 (smallest prime) */

    while(primeCount < n)
    {
        count = 0;    /* count of divisors */

        /* Check if num is prime */
        for(i = 2; i < num; i++)
        {
            if(num % i == 0)
            {
                count++;   /* num has a divisor, not prime */
                break;
            }
        }

        /* If no divisors found, it is prime */
        if(count == 0)
        {
            printf("%d\n", num);
            primeCount++;
        }

        num++;   /* move to next candidate */
    }

    getch();
}

Sample Output

Enter how many prime numbers to display: 5
First 5 prime numbers are:
2
3
5
7
11

Explanation of Key Steps

StepDescription
Read nUser inputs how many primes are needed
primeCount = 0Tracks how many primes have been printed
num = 2Candidate number starts at 2
Inner for loopChecks divisibility of num from 2 to num-1
count == 0If no divisor found, num is prime; print it and increment primeCount
num++Move to the next candidate number

Note: The nested loop structure follows the concept of nesting of loops as described in the course notes, where one loop is written inside the body of another loop.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.