Learn to print all prime number between two given number C++

In this article, you’ll learn how to print all prime number between two given number in C++ language without giving input from the keyboard or giving input from the keyboard.

Q: what is the prime number

Ans: A natural number which only divided by itself and 1 is called a prime number and you also say that a prime number is a natural number which is greater than 1 and cannot be formed by multiplying two natural number.

  • 1 is not a prime number.
  • 2 is the smallest prime number and only even prime number.
  • Example of prime number 2,3,5,7,11,13 etc.

 To print all prime number between two given number we generally use the following steps:

  • First, we take two number then add 1 in the first number and subtract 1 in the second number to check prime number between two intervals number.
  • We use two for loop first, for loop for checking all number between the intervals and second for loop to check prime number.
  • If second for loop is true, then it means the number is not a prime number and increments the number check again
  • If second for loop is false, then it checks again
  • if(i==x) then it a prime number and check again for the first for loop.

Example 1: write a program in C++ language to print all prime number between two given number, without input from keyboard

#include<iostream>

using namespace std;

int main()

{

int f1=3,f2=60,x,i;

for(x=f1+1;x<=f2-1;x++){

       for(i=2;i<x;i++)

       if(x%i==0)

       break;

       if(i==x)

       cout<<“\n”<< x;

  }

 return 0;

}

 

The Output of this program:

 

5

7

11

13

17

19

23

29

31

37

41

43

47

53

59

 

Example 2: write a program in C++ language to print all prime number between two given number, with input from the keyboard

 

Solution:

#include<iostream>

using namespace std;

int main()

{

int f1,f2,x,i;

cout<<“Enter first number: “;

cin>>f1;

cout<<“Enter second number: “;

cin>>f2;

for(x=f1+1;x<=f2-1;x++){

for(i=2;i<x;i++)

if(x%i==0)

break;

if(i==x)

cout<<“\n”<< x;

}

return 0;

}

 

The Output of this program:

Enter first number: 1

Enter second number: 100

 

2

3

5

7

11

13

17

19

23

29

31

37

41

43

47

53

59

61

67

71

73

79

83

89

97

 

Example 3: write a program in C++ language to print all prime number including two given number, with input from keyboard Solution:

#include <stdio.h>

#include <conio.h>

int main()

{

  int f1,f2,x,i;

  printf(“Enter first number: “);

  scanf(“%d”,&f1);

  printf(“Enter second number: ” );

  scanf(“%d”,&f2);

  for(x=f1;x<=f2;x++){

       for(i=2;i<x;i++)

       if(x%i==0)

       break;

       if(i==x)

       printf(“%d “,x);

  }

  return 0;

}

 

The output of this program:

Enter first number: 2

Enter second number: 23

 

2

3

5

7

11

13

17

19

23

Program to a number is prime or not in cpp

Leave a Reply

Your email address will not be published. Required fields are marked *

itetrade.com