Getting straight to it, how do I know when I need to initialize a variable in the declaration line?
Ex:
The program below prompts the user for an integer, reads it and then prints out all of the prime numbers between 3 and the number entered. The declared variables are 'number', 'x', 'y', 'm' and 'n'. I know that the variables 'm' and 'n' are initialized at the beginning of the for loops. What I currently think is going on is that I don't need to initialize 'number' because it's being initialized at the cin statement. Is this right? I sort of understand why I need to initialize 'y' to zero (to make the program work properly. Another int will compile and run, but have incorrect output), but what I don't understand is why I don't need to initialized the x variable. The program compiles and runs fine without it, but if I don't initialize y I get a Break error stating that y is not initialized.
//Program to read an integer that is greater than 2, then finds
//and prints all of the prime numbers between 3 and the number
//entered.
#include <iostream>
usingnamespace std;
int main()
{
int number, x, y (0);
cout << "Enter a number and the program will list all prime numbers below it: ";
cin >> number;
for (int n = 3; n <= number; n++)
{
for (int m = 2; m <= n; m++)
{
x = n % m;
if (x == 0)
y++;
}
if (y == 1)
cout << n << " is a prime number." << endl;
else
y = 0;
}
system("pause");
return 0;
}
If you do not initalize a value for a variable it will have the value last kept in memory. So say you do something like
1 2 3
int number;
cout << "Number + 1 = " << number + 1 << endl;
What will the output be? We do not know what number is by default they are not initalized to 0. So you should initalize it in this case.
Also cin does not initalize the variable number. It assign a value to the uninitialized variable. You were not directly modifying the old value but instead assigning a new value so that is fine. But in the earlier example we were trying to directly modify the old value which was undefined.
Also, one more question and something that I just noticed;
Do I not get an error stating that x is not initialized because is being set equal to quotient of two variables (m & n) that are initialized to 2 and 3, respectively? (ie: x = n % m)?
In your code you are assigning the value of n % m to x before using it. That's why the program runs fine because there's already a value in x when you compare it to 0.
Note: That wouldn't have been possible if you hadn't previously assigned values to both n and m.