In order to understand why your code is wrong and how you can fix it, you should first understand the concept of variables.
Before you can assign a value to a variable, you have to declare it, which you do by typing the data type you want the variable to use (like int
or char
, for example), followed by variable name you choose, and, finally, a semicolon.
This is an example of declaration:
int some_variable;
You can also initialize the variable (assign it an initial value) on the same line, by typing the assignment operator (=
) and the value between the variable name and the semicolon. This is an example of initialization:
int some_variable = 10;
Here, you are creating a variable of type int
called some_variable
, and assigning it an initial value of ten.
Finally, after you have declared a variable, you can change its value by typing the name of the variable, the assignment operator and the value you want to use, like so:
some_variable = 20;
As you can see, there is no need to specify the data type again, since you only have to do so when you declare the variable. In fact, specifying the data type again can lead to unexpected errors, so be careful not to do it.
You can see that typing
int some_variable = 10;
is the same as typing
int some_variable;
some_variable = 10;
The difference between these two approaches is that the former takes up one less line, so it's a little more readable.
Hopefully now you can see why using for (j = 0; j < p + 2; j++)
is wrong, and why declaring j
outside of the for loop solves your issue.
But although declaring j
outside of the for loop is a valid solution, it's not the best, and this is because of the concept of variable scope.
Generally, a variable is only available to use within the pair of curly braces it was declared in. Look at the following example:
#include <stdio.h>
int main(void)
{
// This variable will only exist inside main
var x = 10;
printf("%i\n", x); // Works fine, because x is being used within the same scope it was declared in
while (true)
{
printf("%i\n", x); // Also works, because we are still inside main
}
}
int other_function(void)
{
printf("%i\n", x); // This will produce an error, because we are no longer inside of main and there are no variables named x inside this function
}
As a general rule, you should declare variables in the most reduced scope possible, like so:
int main (void)
{
// This variable is only used within the while loop, so it should be declared there
int x = 10;
while (true)
{
printf("%i", x);
}
}
As you can see, the variable x
is only used within the scope of the while loop, so it should be declared there.
Now you should understand why declaring j
inside the for loop (like this: for (int j = 0; j < p + 2; j++)
is better than declaring it outside of it.
Please let me know if you understand, and tell me if you have any questions.
for(int j=0; j < p + 2; j++)
?