Focus on one part of your program at a time, and test it before adding more to the program.
For example, start with just:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// Example program
#include <iostream>
using namespace std;
int main()
{
int x, arr[x];
cin>>x;
cout<<"Enter Array Elements: "<<endl;
for(int i=0; i<x; i++){
cin>>arr[i];
}
for(int i = 0; i < x; i++)
{
cout << arr[i] << '\n';
}
}
|
This unfortunately is already wrong (although might compile on gcc). When you declare your array, arr[x], the value of x at that point is not defined. Furthermore, the size of a C-style array needs to be a compile-time constant.
You either need to use a dynamic array like a vector, or use an array with a large enough max size.
e.g.
int arr[1000];
Second, let's take a look at just your prime function in isolation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// Example program
#include <iostream>
using namespace std;
int is_prime(int num){
if (num <= 1){
return 0;}
for (int j = 2; j <= num/2; j++){
if (num % j == 0){
return 0;
}
else{
return 1;
}
}
}
int main()
{
for (int i = 0; i < 20; i++)
{
std::cout << i << " : " << is_prime(i) << '\n';
}
}
|
0 : 0
1 : 0
2 : 0
3 : 0
4 : 0
5 : 1
6 : 0
7 : 1
8 : 0
9 : 1
10 : 0
11 : 1
12 : 0
13 : 1
14 : 0
15 : 1
16 : 0
17 : 1
18 : 0
19 : 1 |
Notice anything? Starting at i = 4, your algorithm is essentially just an "is_odd" function, not an "is_prime" function. This is because you are ALWAYS returning either a 0 or a 1 after the first iteration, when j = 2 in your cp function.
PS: What happens when num == 3?
____________________________________
Other things:
- you have the same issue with your parr array, and a similar issue with your farr array.
c=0, farr[c+1][2];
The size of your farr array is [1][2], regardless of what you later change c to be.
1 2 3 4 5 6
|
for(i=0; i<x; i++){
r=cp(arr[i]);
if(r==1)
parr[c]=arr[i];
c++;
}
|
Your indentation here is misleading. The c++ line is not a part of your if statement.
farr[j][2]++;
Regardless of the value of j, this is going out of bounds because the valid inner array indices are only 0 and 1 (the size of that dimension is 2).
I would re-write your code and just start small. Focus first on simply getting and saving correct user input, then focus on how to tell if a number is prime, then focus on the second array that stores pairs of numbers.