I know the answer for this doesn't change anything, I just want to know how it works...
I'm just starting with c++ and looking at basic nested loops at the moment.
My understanding is that the outer loop writes the first # in each row, at which point the inner loop writes the 2nd, 3rd, 4th and 5th # before ending line and looping back to the outer, row loop for its second run and so on.
I wanted to know for the following script does
the inner loop overwrite the 1st column on each run which has been already been executed by the 'row' outer loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//5X5 # Square
#include <iostream>
usingnamespace std;
int main ()
{
for (int row =1; row <=5; ++row) {
for (int col =1; col <=5; ++col) {
cout << "#"; }
cout <<endl;}
return 0;
}
Any replies much appreciated
#include <iostream>
usingnamespace std;
int main ()
{
for (int row =1; row <=5; ++row) {
for (int col =1; col <=5; ++col) {
cout << "#"; // this is what the inner loop does
}
cout <<endl; // this output is by the outer loop
}
return 0;
}
The inner loop repeats only one thing (5 times): the cout << "#";
The outer loop repeats two things:
1. A for statement (i.e. the inner loop)
2. The cout <<endl;
Nothing "mirrors" anything. I have no idea what that even means.
In a for loop, you define which lines of code execute within the loop; in other words, you define which lines of code will be executed every time the loop iterates.
In your inner loop, you have defined that the following code will be executed every time the loop iterates:
cout << "#";
In your outer loop, you have defined that the following code will be executed every time the loop iterates:
1 2 3 4
for (int col =1; col <=5; ++col) {
cout << "#";
}
cout <<endl;
You would help yourself enormously if you adopted a clear and sensible indentation style. This would help you to see at a glance exactly how the logic of your code works.