The Wayback Machine - https://web.archive.org/web/20241118012627/https://www.geeksforgeeks.org/program-to-print-first-10-prime-numbers/
Open In App

Program to print first 10 prime numbers

Last Updated : 23 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Output Format:

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:

C++
#include <iostream>;
using namespace std;

// Function to check if a number is prime or not
bool isPrime(int N)
{
    for (int i = 2; i < N; i++) {
        if (N % i == 0)
            return false;
    }
    return true;
}
int main()
{
    // Variable to store number of primes printed so far
    int cnt = 0;
  
    // Variable to store the number to be checked for prime
    int num = 2;
  
    // Iterate till we have printed the first 10 primes
    while (cnt < 10) {
        // Prime Check
        if (isPrime(num)) {
            cout << num << endl;
            cnt++;
        }
        num++;
    }
}
Java
public class PrimeNumbers {
    // Function to check if a number is prime or not
    public static boolean isPrime(int N) {
        for (int i = 2; i < N; i++) {
            if (N % i == 0) {
                return false;
            }
        }
        return true;
    }

    // Main function
    public static void main(String[] args) {
        // Variable to store the number of primes printed so far
        int cnt = 0;
        // Variable to store the number to be checked for prime
        int num = 2;

        // Iterate until we have printed the first 10 primes
        while (cnt < 10) {
            // Prime Check
            if (isPrime(num)) {
                System.out.println(num);
                cnt++;
            }
            num++;
        }
    }
}
Python
# Function to check if a number is prime or not
def is_prime(N):
    for i in range(2, N):
        if N % i == 0:
            return False
    return True

# Main function
def main():
    # Variable to store the number of primes printed so far
    cnt = 0
    # Variable to store the number to be checked for prime
    num = 2

    # Iterate until we have printed the first 10 primes
    while cnt < 10:
        # Prime Check
        if is_prime(num):
            print(num)
            cnt += 1
        num += 1

# Run the main function
if __name__ == "__main__":
    main()
C#
using System;

class Program
{
    // Function to check if a number is prime or not
    static bool IsPrime(int N)
    {
        for (int i = 2; i < N; i++)
        {
            if (N % i == 0)
                return false;
        }
        return true;
    }

    static void Main()
    {
        // Variable to store the number of primes printed so far
        int cnt = 0;
        // Variable to store the number to be checked for prime
        int num = 2;

        // Iterate until we have printed the first 10 primes
        while (cnt < 10)
        {
            // Prime Check
            if (IsPrime(num))
            {
                Console.WriteLine(num);
                cnt++;
            }
            num++;
        }
    }
}
JavaScript
// Function to check if a number 
// is prime or not
function isPrime(N) {
    for (let i = 2; i < N; i++) {
        if (N % i === 0)
            return false;
    }
    return true;
}

// Variable to store number of
// primes printed so far
let cnt = 0;

// Variable to store the number 
// to be checked for prime
let num = 2;

// Iterate till we have printed 
// the first 10 primes
while (cnt < 10) {
    // Prime Check
    if (isPrime(num)) {
        console.log(num);
        cnt++;
    }
    num++;
}

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)



Similar Reads

Program to print first 10 even numbers
Program to print first 10 even numbers. A number is even if it is divisible by 2 for example 4, 100, 24 etc. Output Format: 0 2 4 6 8 10 12 14 16 18 Approach: Checking Parity using Modulo operator(%) Using the modulo % operator we can find the remainder of any number when divided by 2, giving us the parity according to two cases: remainder = 0: Eve
3 min read
Program to print first 10 numbers of Fibonacci series
Find the first 10 numbers of Fibonacci series. The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ........ Approach: To solve the problem, follow the below idea: We can take two variable
3 min read
Program to print first 10 perfect squares
Write a program to print the first 10 perfect squares. A perfect square is an integer which is the square of some other integer, or we can say that it is a second exponent of an integer. Output format: 1 4 9 16 25 .... Approach: We know that the first 10 perfect squares will be square of 1, square of 2, square of 3... till square of 10. So, iterate
2 min read
Program to print all three digit numbers in ascending order
Write a program to print all the three-digit numbers in ascending order. Output Format: 100 101 102...till 999 Approach: Using for Loop to print all the three Digit Numbers: Use for loop to iterate from the smallest three-digit number, that is 100 till we reach the largest three-digit number, that is 999 and, in every iteration, print the number. A
3 min read
Program to print all two-digit numbers in descending order
Write a program to print all the two-digit numbers in descending order, that is print all the two-digit numbers from largest to smallest. Output format: 99 98 97 96 95 94 93 ..... 13 12 11 10 Approach: We know that the largest two-digit number is 99 and the smallest two-digit number is 10. So, we can start from 99 and then keep on decreasing the nu
2 min read
Program to print numbers having remainder 3 when divided by 11
Write a program to print all numbers from 1 to 1000 which leave a remainder of 3 when divided by 11. Output format: 3, 14, 25, 36, 47.... 993 Approach: To solve the problem, follow the below idea: The problem can be solved by simply using for loop and iterate from 3 up to the 1000 and increment by 11 as we are dividing by 11. Step-by-step approach:
4 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Program to Print the Trapezium Pattern
Given 'num' which indicates number of lines.The task is to print a trapezium pattern in num lines.Examples: Input : 4 Output : 1*2*3*4*17*18*19*20 5*6*7*14*15*16 8*9*12*13 10*11 Input : 2 Output : 1*2*5*6 3*4 Algorithm : step 1. To read num which indicates the number of lines. step 2.We are diving the pattern into 2 halves that is LHS part and the
6 min read
Recursive program to print triangular patterns
We have discussed iterative pattern printing in previous post. Examples: Input : 7 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * Algorithm:- step 1:- first think for the base condition i.e. number less than 0 step 2:-do the recursive calls till number less than 0 i.e:- printPartten(n-1, k+1); step 3:-print the spaces step 4:-then
8 min read
Program to print multiplication table of any number in PHP
In this article, we will see how to print the multiplication table of any given number using PHP. To make the multiplication table, first, we get a number input from the user and then use for loop to display the multiplication table. We use HTML and PHP to display the multiplication table. The HTML part is used to design a form to get the input fro
1 min read
Write a Program to Print 2024 Calendar
Write a Program to print the 2024 Calendar. Example: 2024 Calendar: January 2024 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 February 2024 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 March 2024 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 1
15+ min read
Write a Program to Print Holiday Calendar 2024
Write a program to print the Holiday Calendar 2024. Output Format (Holiday Calendar 2024): January 26 - Friday - Republic DayMarch 25 - Monday - HoliMarch 29 - Friday - Good FridayApril 11 - Thursday - Id-ul-FitrApril 17 - Wednesday - Ram NavmiApril 21 - Sunday - Mahavir JayantiMay 23 - Thursday - Buddha PurnimaJune 17 - Monday - Id-ul-Zuha (Bakrid
5 min read
Program to Print Inverted Left Half Pyramid Pattern (Star Pattern)
Given an integer N, the task is is to print a left half pyramid pattern with N rows. In this pattern, the first row contains N stars, the second row contains N - 1 stars, and so forth until the Nth row, which contains only 1 star. All the stars are aligned to the right. Examples: Input: 3Output: *** ** * Input: 5Output: ***** **** *** ** * Approach
4 min read
Program to Print Inverted Right Half Pyramid Pattern (Star Pattern)
Given an integer N, print N rows of inverted right half pyramid pattern. In inverted right half pattern of N rows, the first row has N number of stars, second row has (N - 1) number of stars and so on till the Nth row which has only 1 star. Examples: Input: n = 5Output:*************** Input: n = 3Output:****** Approach: The problem can be solved us
3 min read
Program to Print Right Half Pyramid Pattern (Star Pattern)
Given an integer N, print N rows of right half pyramid pattern. In right half pattern of N rows, the first row has 1 star, second row has 2 stars and so on till the Nth row which has N stars. All the stars are left aligned. Examples: Input: 3Output: ****** Input: 5Output: *************** Approach: The problem can be solved using two nested loops. T
3 min read
Program to print ASCII Value of a character
Given a character, we need to print its ASCII value in C/C++/Java/Python. Examples : Input : a Output : 97 Input : DOutput : 68 Here are few methods in different programming languages to print ASCII value of a given character :  Python code using ord function : ord() : It converts the given string of length one, returns an integer representing the
4 min read
Program to Print Butterfly Pattern (Star Pattern)
Given an integer N, print N rows of Butterfly pattern. Examples: Input: 3Output: * *** ********* *** * Input: 5Output: * *** ***** ******* ***************** ******* ***** *** * Approach: The problem can be solved using three nested loops inside an outer loop. The outer loop will run for the rows, the first inner loop will print the stars, the secon
6 min read
Program to Print Inverted Full Pyramid Pattern (Star Pattern)
Given an integer N, the task is to print a pattern of N rows representing an inverted full pyramid. In this pattern, the first row has (2 * N - 1) stars, the second row has (2 * N - 3) stars, and so on until the Nth row, which has only 1 star. All stars are center-aligned. Examples: Input: 3Output: ***** *** * Input: 5Output: ********* ******* ****
4 min read
Program to print all multiples of 7 till 1000
Write a program to print all multiples of 7 till 1000. Output Format: 7, 14, 21, 28, 35 ..... 994 Approach: To solve the problem, follow the below idea: The approach of this program is to run a loop starting from 7 and in each iteration add 7 to the current multiple to get the next multiple. Step-by-step algorithm: This program uses a for loop to i
3 min read
Program to print the number of days in a given year
Write a program to print the number of days in a given year. Examples: Input: 2023Output: 365Explanation: The year 2023 is not a leap year, therefore the number of days are 365. Input: 2024Output: 366Explanation: The year 2024 is a leap year, therefore the number of days are 366. Approach: To solve the problem, follow the below idea: To determine t
4 min read
Program to Print Multiplication Table of a Number
Given two positive integers N and K, the task is to print the Multiplication table of N till Kth multiple. Examples: Input: N = 6, K = 5Output:6 * 1 = 66 * 2 = 126 * 3 = 186 * 4 = 246 * 5 = 30 Input: N = 9, K = 3Output: 9 * 1 = 9 9 * 2 = 189 * 3 = 27 Approach: The problem can be solved by running a loop from i = 1 to i = K and for every iteration p
3 min read
Program to Print Full Pyramid Pattern (Star Pattern)
Given an integer N, the task is to print a full pyramid pattern with N rows. In this pattern, each row contains an odd number of stars, ranging from 1 star in the first row to (2 * N - 1) stars in the Nth row. All the stars are center-aligned. Examples: Input: 3Output: * ******** Input: 5Output: * *** ***** **************** Approach: The problem ca
4 min read
Program to print the name of month using the month number | Menu-Driven
Your task is to design a menu-driven program that asks the user to input a month number, and the program prints the name of the month. A menu-driven program is a type of computer program that allows users to interact with it by selecting options from a menu. Instead of typing commands or code, users navigate through a series of menus that present a
7 min read
Write a program to print 1 to 100 without using any numerical value
Write a program to print numbers from 1 to 100 without using any numerical value. Output Format: 1 2 3 4 5 6 7 8 9 10 11 ....... 97 98 99 100 Approach: Use ASCII characters to make count of numbers i.e. 'A' character has ASCII value equal to 65 and 'B' has ASCII value 66, so we can subtract 'A' from 'B' to get the starting value 1. Now, we can run
3 min read
Program to Print Left Half Pyramid Pattern (Star Pattern)
Given an integer N, the task is to print N rows of left half pyramid pattern. In left half pattern of N rows, the first row has 1 star, second row has 2 stars and so on till the Nth row which has N stars. All the stars are right aligned. Examples: Input: 3Output: * ***** Input: 5Output: * ** *** ********* Approach: The problem can be solved using t
4 min read
Program to find the sum and difference of two numbers
Given two Integers A and B, your task is to find the sum and difference of two numbers. Examples: Input: A = 4, B = 9Output: Sum = 13 and Difference = -5Input: A = -3, B = -2Output: Sum = -5 and Difference = -1 Approach: The problem can be solved using arithmetic operators. Operations on Numbers: Addition (+): This operation is used to add the inpu
3 min read
Program to find the average of two numbers
Given two Integers A and B, your task is to find the average of two numbers where the average is given by the formula:average(A, B) = (A+B)/2 Examples: Input: A=5, B=3Output: 4Explanation: Average(A,B) = (A+B)/2 = 8/2 =4 Input: A=10, B=5Output: 7.5Explanation: Average(10, 5) = (10 + 5)/2 = 15/2 = 7.5 Approach: To solve the problem, follow the below
3 min read
Programming or DSA: Which one should I learn first?
Programming and Data Structures and Algorithms (DSA), both are important to learn because they form the foundation of creating computer programs and solving problems effectively. But deciding where to start in computer science can be tricky, i.e. Should you learn Programming first or jump into Data Structures and Algorithms (DSA) directly? Table of
10 min read
Print Happy New Year 2024
Write a program to print "HAPPY NEW YEAR 2024" pattern. Approach to print Happy New Year 2024:Here are step-by-step instructions to create a program that prints "HAPPY NEW YEAR 2024" in a pattern: Set up your development environment: Ensure that you have a compiler installed on your machine. You can use an integrated development environment (IDE) l
9 min read
TCL script to find sum of n natural numbers using looping statements
In this article, we will discuss the overview of TCL script and will cover the TCL script to find the sum of n natural numbers using looping statements with the help of an example. Let's discuss it one by one. Pre-requisite -You can go through this article to understand a few basics through this link. https://www.geeksforgeeks.org/basics-of-ns2-and
3 min read
Article Tags :
three90RightbarBannerImg