I found 2 mistakes – Your answer is coming to be 0 always because in the array [4,7,8,9] 9 is the largest biggest non prime number and there is no prime number greater than 9 in your array.
if the input array is [4,7,8,9,11] the output is 11 as 11 is smallest prime number greater than 9.
Second mistake instead of using this
if(CheckPrimeNum(a[i])==2 && a[i]> BiggestNotPrime(a,n))
SmallestPrimeLocation =i;
break;
You should be using
if(CheckPrimeNum(a[i])==2 && a[i]> BiggestNotPrime(a,n))
{ SmallestPrimeLocation =i;
break;
}
This is because your break statement was oustide if condition and loop was getting executed just once.
However you have complicated a simple task, a simpler code can be something like this
Working code-
#include <bits/stdc++.h>
using namespace std;
void TypeIn(int a[] ,int &n)
{
cout<< "\nType in n: ";
cin >> n;
for(int i=0; i<n; i++)
{
cout << "a[" << i << "]= ";
cin >> a[i];
}
}
bool isPrime(int n)
{
// Corner case
if (n <= 1) return false;
// Check from 2 to n-1
for (int i=2; i<n; i++)
if (n%i == 0)
return false;
return true;
}
int BiggestNotPrime(int a[], int n)
{
int BiggestNotPrimeNum =0;
for( int i=0; i<n; i++)
{
if(!isPrime(a[i]))
{
BiggestNotPrimeNum = a[i];
}
}
return BiggestNotPrimeNum;
}
int main()
{
int n;
int a[100];
TypeIn(a,n);
//sorting the array is important
sort(a,a+n);
int SmallestPrimeLocation =-1;
int BiggestNotPrimeNum = BiggestNotPrime(a,n);
for(int i=0; i<n; i++)
{
if(a[i]> BiggestNotPrimeNum && isPrime(a[i]))
{
SmallestPrimeLocation =i;
break;
}
}
if(SmallestPrimeLocation ==-1)
{
cout << "No number found"<<endl;
}
else
{
cout<<a[SmallestPrimeLocation]<<endl;
}
}
solved The result of my code is zero and I don’t know why