Using c++, write a program for Checking whether the number is prime within an interval
Note: The program isn't working. Can't find what's wrong.
int p,q,j,i,n; int r=1;
cout<< "Enter any range to find out prime numbers within it. Initial range: "; cin>>p; cout<< "Final range: "<<endl; cin>>q;
for(j=q;j>=p; j--)
{
for(i=2;i<q;i++)
{
int s;
s=q%i;
if(s!=0)
{
r=s;
// cout<<"The number "<<q<<" is divisible by "<<i<<endl; This line will find factors of all numbers..unnecessary
}
In general: Explain what "isn't working" means. What is the expected behavior, and what is the actual behavior? Even better would be to also show us a compileable example that reproduces the issue without us having to edit the code.
- Your second for loop goes from 2 to the 'q'. But presumably, the current number that you are testing the primality of is 'j' (the outer for loop variable).
- You have your j, i, r variables declared at broader scopes than necessary. Specifically, your r variable's value is not reset each inner loop.
Hint: You can hit "edit post", highlight your code and then press the <> formatting button. This will not automatically indent your code. That part is up to you.
I've found it's easiest to copy and paste pre-indented code directly from the IDE, that way it is already properly formatted.
You can use the "preview" button at the bottom to see how it looks.
You can take a logically independent subtask and implement it in a function. Then set the rest of the program to call that function. That makes the calling code simpler and you can better focus on its logic.
What are the logical tasks in your program?
What does "Check whether the number is prime within an interval" mean?
Does it mean: "Which numbers within an interval are prime?"
That has tasks:
* One does something with ever number within an interval
* Another tests whether one number is prime
The "something" of the first task tests a number and shows the result.
A function (or function object) that takes some data, evaluates some condition with that data, and returns boolean (true or false) is called predicate. An example:
1 2 3 4
// isPrime returns true, if 'val' is a prime
bool isPrime( int val ) {
// some code
}