Print Prime Numbers b/w Two Given Numbers

  • Context: Comp Sci 
  • Thread starter Thread starter Vishalrox
  • Start date Start date
  • Tags Tags
    C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
Vishalrox
Messages
20
Reaction score
0
Wanted help in c++ !

Program to print the number of prime numbers between two user given numbers.

MY ATTEMPT TO SOLUTION :
I hv found how to print the prime numbers between two given numbers but couldn't print the number of prime numbers between two given numbers.

#include<iostream.h>
#include<conio.h>
void main()
{
int n,x,i,j;
count<<"Enter the lower range";
cin>>n;
count<<"Enter the upper range";
cin>>x;
for(i = n;i<=x;i++)
{
for(j = 2;j<=i-1;j++)
{
if(i % j !== 0)
{
count<<i;
count<<"\n";
}
}
}
getch();
}
 
Physics news on Phys.org


Vishalrox said:
I hv found how to print the prime numbers between two given numbers

The code you posted just prints a number every time i is found to not have a specific factor.
You still need to do something such as check that i % j !== 0 for all j. This could be done with a boolean external to the innermost loop.

Once you have done this, you may use an integer external to the outer loop to count the number of primes.

Also, iostream.h is not part of standard C++. Instead, please use

Code:
#include <iostream>
 


I doubt that this code you presented will even compile. A few comments on the coding (since the problem with the algorithm has already been mentioned):
- I don't think I have ever seen the operator "!==". Are you sure you don't mean "!=" ?
- cout<<"\n" can (and should) in many cases be replaced with cout<<endl. "cout<<i; cout<<"\n";" can be combined in a single line "cout<<i<<endl;".
- You should add the line "using namespace std;" before the start of the main routine.
- I made it a habit to give my variables sensible names, a habit that I could also convince my students of (by simply not giving points for parts of the code that I don't understand :P). Sensible variable names would be n->lower, x->upper, i->candidate, j->divisor. That should make your code much more readable.
- Another related good habit is to define variables as local as possible. In c++ you do not need to specify all variables being used at the start of the routine (you had to do that in C). Rather than writing
Code:
int i;
...
for(i=lower; i<=upper; i+=1) { ...
you can write
Code:
for(int i=lower; i<=upper; i+=1) { ...
Apart from being shorter it also improves the readability of code overall.