I have some trouble with the parameters (this is my first attempt of using two functions) when constructing the function and calling it.
Here is the debugger's error:
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp||In function 'bool isPrime(int*)':|
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp|11|error: 'i' was not declared in this scope|
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp|16|error: 'i' was not declared in this scope|
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp||In function 'int main()':|
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp|34|error: too few arguments to function 'bool isPrime(int*)'|
I:\c++\11_Tombos feladatok-beszuras_torles\19.cpp|9|note: declared here|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
And here is the code:
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
bool isPrime(int t[])
{
for(int j=2; j<=sqrt(t[i]); j++)
{
if(t[i]%j==0)
return false;
}
if(t[i]<2)
return false;
return true;
}
int main()
{
int t[50], n, i;
cout<<"Size of array: ";
cin>>n;
for (int i=1; i<=n; i++)
{
cout<<i<<". Element: ";
cin>>t[i];
}
i=1;
while(i<=n)
{
if(isPrime())
{
for(int j=n; j>=i+1; j--)
{
t[j+1]=t[j];
}
t[i+1]=99;
n++;
i=i+2;
}
else
{
i++;
}
}
for(int i=1; i<=n; i++)
{
cout<<t[i]<<", ";
}
cout<<"\n";
system("pause");
return 0;
}
I know that system("pause") is slow and it's not recommended etc. Don't blame me for using it (suggest something else instead).
Here's a code review. :)
isPrime
should take an int t
parameter, not an array. You also use t[i]
in this function, but i
is out of scope! You declared i
in main
. Replace both t[]
and t[i]
with just t
. Or, even better, call it number
instead so it's super clear.int i
on the first line of main
, and then again in the for loop directly beneath it that initializes the t
array. I'm surprised this didn't cause a compilation error.for(int i = 1;...
, you will miss the first element of the array every time! Remember: arrays are indexed from 0, so those should be for(int i = 0;...
.cin >> n
in main
). What if I enter 100? Your array t
in main
holds 50 integers, so t[100]
would cause your program to crash with a segfault.main
, the line if(isPrime())
won't compile because you defined isPrime
to take a parameter, but you aren't calling it with any parameters. I think you meant if(isPrime(i))
?int j = n
, then try to access t[j+1]
, which isn't allocated. This will also cause your program to crash.n++
in the while loop? I can see this causing problems/unintended behavior because this is the bound on your while loop.#include <stdlib.h>
use #include <cstdlib>
, and instead of #include <math.h>
use #include <cmath>
.There are probably a few more bugs/issues, but that should get you moving. Let us know what you come up with!