| What's goin on with these braces? I've written a program that inputs the number of rows and columns, and which character to print and then prints a matrix. The code works fine, but I did some experimenting with removing braces like this:
for(int i = 0; i < rows; i++)
// opening brace would go here
for(int j = 0; j < columns; j++)
cout << theChar;
cout << "\n";
// closing brace would go here
return 0;
Like I said if I don't include the braces it will print like this:
**************** and so on.
I think that's because the body of the for loop expects only one statement. And the body of the inner loop actually has two statements in it. So when the inner loop is done printing 5 * characters instead of going to the "\n statement instead it goes to the outer loop again increments 0 to 1 and then it goes to the inner loop again and starts over. Correct me if I'm wrong.
Now if I do the opposite and add braces to the inner loop, so both the outer and inner loop have braces so the code looks like this:
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
cout << theChar;
cout << "\n";
}
}
return 0;
Now it will print like this:
*
*
*
*
*
*
and so on.
Is that because with the addition of the inner braces both statements are executed in succession? Like it will output a * character and then go to a newline. Then output a * character and then go to a new line. Then output a * character... and so on?
I think I may be on the right track here but want to know for sure. |