I've read some previous questions about the use of curly brackets, from my understanding it's ok to not use the curly brackets if you have only one line but if you were to use many lines of code you would need to use brackets.
I have an assignment and the instructor does require us to use the brackets for every situation for good habit. He also allows us to research and use sample code.
Now, my question is, I found some sample code that does not use brackets. When i try to add the brackets into the code it makes my output incorrect. Can someone explain to me how to correctly use the curly brackets in multiple lines of code and suggest a recommendation on how i may achieve the results i'm looking for.
Here is the code when the output is correct:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{
if(i == n)
{
for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
for(int j = 1; j <= n; j++) cout << '*'; cout << endl;
}
else
{
for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++) cout << '*'; cout << endl;
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}
and when i try to "clean it up" looking like this:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
{
if(i == n)
{
for(int j = 1; j <= n; j++)
{
cout << '*';
cout << endl;
}
for(int j = 1; j <= n; j++)
{
cout << '*';
cout << endl;
}
}
else
{
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}
The problem is you put too much in the printing loops:
for(int j = 1; j <= i; j++)
{
cout << '*';
cout << endl;
}
Should be:
for(int j = 1; j <= i; j++)
{
cout << '*';
}
cout << endl;
Loops without curly braces can only contain a single statement. This means the end-of-line print using cout
is only called when the loops end.
This is the full code using curly braces:
void printStars(int i, int n)
// The calling program invokes this function as follows: printStars(1, n);
// n >= 1
{
if(i == n)
{
for(int j = 1; j <= n; j++){
cout << '*';
}
cout << endl;
for(int j = 1; j <= n; j++){
cout << '*';
}
cout << endl;
}
else
{
for(int j = 1; j <= i; j++){
cout << '*';
}
cout << endl;
printStars(i+1, n); // recursive invocation
for(int j = 1; j <= i; j++){
cout << '*';
}
cout << endl;
}
} // printStars
int main() {
int n;
int i=0;
cout << "Enter the number of lines in the grid: ";
cin>> n;
cout << endl;
printStars(i,n);
return 0;
}