Write a program that will display all prime numbers from the given range. The program must satisfy the following requirements:
a. ask the user of range to display
b. contains the following function:
i. checkRange() – a functions that checks if the entered range is correct or not. A message will be displayed if the range is invalid.
ii. displayPrime() – a function that displays all prime numbers in the given range
NOTE: you will provide the parameter(s) for each function.
here's the code that i made: there is something wrong in my code. I can't pinpoint what is it
#include <iostream>
using namespace std;
int main()
{
int Prime, strt, end, result;
bool isprime=true;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>strt;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
result = Prime(strt,end);
cout<<"Prime numbers in the given range are: "<<result<<endl;
return 0;
}
int Prime(int strt, int end, int num, isprime)
{
int result;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (num = 2; num <= strt/2; num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime)
cout << strt << ", ";
strt;
}
return result;
}
CodePudding user response:
Here is the answer, there are many issues with the code that I won't go through them, ask if you don't understand something
#include <iostream>
using namespace std;
int prime(int strt, int end)
{
bool isprime;
int count;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (int num = 2; num <= strt/2; num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout << strt << ", ";
count;
}
strt;
}
return 0;
}
int main()
{
int strt, end, result;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>end;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
cout<<"Prime numbers in the given range are: ";
prime(strt,end);
return 0;
}
CodePudding user response:
This is Probably the simplest way I can put it for you.
#include<iostream>
using namespace std;
int check_range(int a,int b)
{
if (a > b)
return 0;
else
return 1;
}
int check_prime(int a,int b)
{
bool isprime;
while (a < b)
{
isprime=true;
if (a == 0 || a == 1)
{
isprime = false;
}
for (int i = 2; i <= a/2; i )
{
if (a % i == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout <<a<<" ";
}
a ;
}
}
int main()
{
int strt,end;
Repeat :
cout<<"Enter the lower limit of range :";
cin>>strt;
cout<<"Enter the upper limit of range :";
cin>>end;
int p = check_range(strt,end);
if (p)
{
check_prime(strt,end);
}
else
{
cout<<"The range is inappropriate.\n";
goto Repeat;
}
}
Hope you would understand.