Tuesday 25 September 2018

Printing n prime numbers in C++

Prime numbers

Prime numbers are those numbers which are divisible by and itself only. A prime number doesn't have any pattern but can be determined by the division process.
      E.g. 2,3,5,7,...etc. (i.e. 7 is divisible by 1 and itself only, so it is a prime number.)
Zero and one (0,1) are neither prime nor composite numbers

Write a program in C++ to input a number from the user and print all the prime numbers up to it.

We need to input a number from the user and print the prime numbers up to that number. We will use a nested for loop to print the numbers. For loop is considered in such a way that each number is divided by all positive integer greater than 1 and less than the number(1<Divisor<Number). If any particular number is not divisible by any divisor, then it is considered a prime number and is printed.

The break statement is jump control statement which transfers the control out of the loop (i.e. the loop terminates). The break statement only terminates the loop which contains the statement.
Syntax:
                  break;

Program


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c=0,n;
clrscr();
cout<<"Enter the number upto which you want to print the prime number=";
cin>>n;
for(a=1;a<=n;a++)
          {  
                  for(b=2;b<a;b++)
                 {
                 if(a%b==0)
                 break;
                 }
          if (b==a)
          cout<<a<<endl;
          }
getch();
}

Output

Program to print prime numbers
PRINTING N PRIME NUMBERS








Explanation

In the above program, our input is 19(i.e. n=19). So the nested for loop will be executed as follows:

a        a<=19               b           b<a                      a%b                       b==a                  Action
1        True                  2           2<1 is false                                          1=2 is false
2        True                  2           2<2 is false                                          2=2 is true          2 is printed.
3        True                  2           2<3 is true           3%2=0 is false          
                                   3           3<3 is false                                          3=3 is true           3 is printed.
4        True                  2           2<4 is true           4%2=0 is true                                      Break.
5        True                  2           2<5 is true           5%2=0 is false                  
          True                  3           3<5 is true           5%3=0 is false   
          True                  4           4<5 is true           5%4=0 is false   
          True                  5           5<5 is false                                          5=5 is true          5 is printed.  

The process is continued till a=19. The required prime number get printed on the screen.                                
        
      


No comments:

Post a Comment