PLAY WITH CODING

Home Basic Program If & Else Loops Conversion Pattern logo

Program Based on Loops

Program to count all prime number in a given range

Input - Output

Input
Enter the range to print Prime Number : 2 35

Output
Total prime number between 2 and 35 are : 11

Algorithm

Step 1: START

Step 2: Declare variable num1,num2,flag and count=0;

Step 3: Input range from user and store it into num1 and num2.

Step 4: Now we have to check each number from low limit number to upper limit number one by one if it is found prime then increment count by 1.

Logic

first for Loop for range incease lower limit by 1 in eacch iteration

second for Loop for check it is prime or not

Step 5: for(int i=num1;i<num2;++i) {

      flag = 0 ;

      for(int j=2;j<=num/2;j++){

           if( i % j == 0){

           flag=1

            break; }

          }

      if flag == 0 && i != 1

        count ++ ;

   }

Step 6: print Count

Step 7: END

CODE


/* Count all prime number in a given range */

#include<stdio.h>
int main()
{
      int num1,num2,flag,count=0;
      printf(" Enter the two range to count prime number : ");
      scanf("%d%d",&num1,&num2);
      printf(" Total prime number between %d and %d are : ",num1,num2);
      for(int i=num1;i<num2;++i)
    {
        flag=0;
        for(int j=2;j<=i/2;++j)
      {
          if(i % j == 0)
        {
            flag=1;
            break;
        }
      }
        if(flag == 0 && i != 1)
        count++;
     }
      printf(" %d",count);
    return 0;
}


/* Count all prime number in a given range */

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
      int num1,num2,flag,count=0;
      cout<<" Enter the two range to count prime number : ";
      cin>>num1>>num2;
      cout<<" Total prime number between "<<num1<<" and "<<num2<<" are : ";
      for(int i=num1;i<num2;++i)
    {
        flag=0;
        for(int j=2;j<=i/2;++j)
      {
          if(i % j == 0)
        {
            flag=1;
            break;
        }
      }
        if(flag == 0 && i != 1)
        count++;
     }
      cout<<count;
    return 0;
}

OutPut

Enter the range to print Prime Number : 2 35

Total prime number between 2 and 35 are : 11