![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
Just like to know why
This code asks the user how many rows he would like and how many columns he would like plus what character he wants to print. Then it uses a nested for loop to print the output:
int main() { int rows, columns; char theChar; cout << "How many rows? "; cin >> rows; cout << "How many columns? "; cin >> columns; cout << "What character? "; cin >> theChar; for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) cout << theChar; cout << "\n"; } return 0; } Now the code works fine. But if I remove the opening brace and closing brace for the for loop, and say input 5 for rows and 5 for columns it will print like this: ************************* I'd like to understand why it does that. Is it because there are actually 2 statements in the body of the inner loop? And without the braces only the cout << theChar statement will run? Just like to be clear on this. |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5
![]() |
it's just executing the next one line of code which is the second nested loop statement. the /n character is ignored until the very end of the program.
that's why we have those pretty braces!
__________________
i put on my robe and wizard hat... Have you ever heard of Plato, Aristotle, Socrates?...Morons. |
|
|
|
|
|
#3 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
I noticed that if I add two more braces like this:
for(int i = 0; i < rows; i++) { for(int j = 0; j < columns; j++) { cout << theChar; cout << "\n"; } } It will print just the opposite like this: * * * * * * and all the way down to 25. Why? |
|
|
|
|
|
#4 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5
![]() |
cuz you print the "*" and then new-line it 25 times. you need to print your whole inner loop before executing the \n and then return to the next iteration of the outer loop.
__________________
i put on my robe and wizard hat... Have you ever heard of Plato, Aristotle, Socrates?...Morons. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|