Help needed with IsPrime function.

Hi!
So, I'm new to C++ and I have a final tomorrow. as i was practicing i encountered this problem: "Write a function, called IsPrime that receives one parameter n, and returns whether the number is prime or not."

So, I've tried it many times, and I get the same error while building it.
this is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
using namespace std;
int IsPrime(int n)
{
	int c;
	for (int i = 2; i < n - 1; i++)
	{
		int c;
		if (n%i != 0)
			continue;
		else
			c = 0;
	}
	if (c == 0) 
		cout << "not prime.";
	else
		cout << "prime.";
	return c;
}
int main()
{
 int n;
	cout << "Please enter a number: ";
	cin >> n;
	IsPrime(n);

}


The problem is I get this error message that says: "Uninitialized local variable 'c' used" that is in line 14.
Please help...
Thank you.
Last edited on
The Error message is straight forward.
On line 14, Variable 'c' is Uninitialized.
You declare a local variable in the for loop int c; and don't set it equal to anything.
So how are you supposed to compare c to something, when you do not know what c is?
Best practice is to Declare a variable, and set it to a value before you use it. Your Else statement may never be triggered and thus c may never equal 0. So it will have garbage in it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include <iostream>
using namespace std;
int IsPrime(int n)
{
	int c;//Declared int c here
	for (int i = 2; i < n - 1; i++)
	{
		int c;//Also declared int c here. Did not initialize either of them. Double declaration is bad
		if (n%i != 0)
			continue;
		else
			c = 0;//You set c equal to a value here
	}
	if (c == 0) 
		cout << "not prime.";
	else
		cout << "prime.";
	return c;//What is the purpose of returning c? Just set to void function since you print result in function
}
int main()
{
 int n;
	cout << "Please enter a number: ";
	cin >> n;
	IsPrime(n);

}
Last edited on
You have two instances of the variable c. line 5 and line 8. The instance at line 8 hides the one at line 5. The instance at line 8 goes out of scope at line 13. At line 14, the instance at line 5 has never been initialized. Get rid of line 8.

A couple of suggestions on style:
1) Make IsPrime() a bool function.
2) Remove the printing from IsPrime().
3) Exit with false as soon as the first even division occurs. No need to check further.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

bool IsPrime(int n)
{   for (int i = 2; i < n - 1; i++)
	{   if (n%i == 0)
			return false;   //  No need to check further 
	}
	return true;    
}
int main()
{   int n;

	cout << "Please enter a number: ";
	cin >> n;
	if (IsPrime(n))
	    cout << "is prime.";
    else
        cout << "is not prime."; 	    
    return 0;
}

Last edited on
Topic archived. No new replies allowed.