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:
#include <iostream>
usingnamespace 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.
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
#include <iostream>
usingnamespace 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);
}
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.
#include <iostream>
usingnamespace std;
bool IsPrime(int n)
{ for (int i = 2; i < n - 1; i++)
{ if (n%i == 0)
returnfalse; // No need to check further
}
returntrue;
}
int main()
{ int n;
cout << "Please enter a number: ";
cin >> n;
if (IsPrime(n))
cout << "is prime.";
else
cout << "is not prime.";
return 0;
}