VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-print-first-10-prime-numbers/

⇱ Program to print first 10 prime numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to print first 10 prime numbers

Last Updated : 23 Jul, 2025

Write a program to print the first 10 prime numbers.
Note: A number N is said to be prime if it has exactly two factors i.e. 1 and the number itself N

:

2, 3, 5, 7, 9...

Approach:

Prime Test: To check whether a number N is prime we can check its divisibility with each number from 2 to N - 1, If it is divisible by any number in this range, we can conclude that N is not a prime number.

Looping until first 10 primes are not found: We can use a while loop to continue our prime check on the numbers until we print the first 10 prime numbers.

Step-by-step algorithm:

  • Maintain a variable cnt = 0 to keep track of number of primes printed so far.
  • Maintain a variable num = 2 to keep track of the number to be checked for prime.
  • Run a loop till cnt is less than 10.
    • If num is prime, increment cnt by 1.
    • Increment num by 1.
  • After cnt becomes 10, we have printed the first 10 prime numbers.

Below is the implementation of the above approach:


Output
2
3
5
7
11
13
17
19
23
29

Time Complexity: O(1) if we consider only fixed number of elements like 10. If number of elements are provided by the user, then it would be O(N^2) and can be optimized using Sieve Algorithm
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: