Garvan Doyle
Garvan Doyle

Reputation: 7

Confused about the use of break in this nested loop

#include <iostream>
using namespace std;
int main()
{
 for(int r = 0; r<3; r++)
    {
       for(int c = 0; c<=r; c++)
       {
         if(c == 1)
           break;
         cout<<'*';
       }
     cout<<endl;
     }

 return 0;
} 

This code outputs:

*
*
*

My question is why is does it not output:

*

*

My logic is that the first loop runs with r = 0. Then calling the inner loop where c = 0. The first if statement is not true and so * is printed. This loop ends resulting in c = 1 as well as the larger loop where r now = 1. The main loop begins again sufficing all conditions but for some reason still prints a * from the inner loop even the the if command instructs a break to be called.

My possible thoughts are that: 1. There are no brackets around the if statement? 2. break; for some reason doesn't break the loop and instead the if statement(idk why this would be the case) 3. Magic?

Any help is appreciated as if its not already clear I am still very novice to the C++ language.

Upvotes: 1

Views: 77

Answers (4)

Mohammad Kanan
Mohammad Kanan

Reputation: 4602

If you restructure the logic, you will find that your inner loop is equivalent to :

for(int c = 0; c < 1 ; c++)
       {
         cout<<'*';
       }

Now, the outer loop will iterate 3 times R->{0,1,2) .. and for all R's, your inner loop gets chance to iterate and only 1 iteration .. Thus you get three * prints.

Upvotes: 1

MoonlitChameleon
MoonlitChameleon

Reputation: 1

The break instruction will interrupt the current for loop on that line. Thus, the programm will continue the execution from the next instruction after that block, which is cout<<endl;.

If no cout<<endl; were executed, your output would have looked like this:

***

To get a blank line, you need to add another cout<<endl; before the break instruction, like this:

#include <iostream>
using namespace std;
int main() {
    for(int r = 0; r<3; r++) {
        for(int c = 0; c<=r; c++) {
            if(c == 1) {
                cout<<endl;
                break;
            }
            cout<<'*';
        }
        cout<<endl;
    }

return 0;
} 

This code will print this:

* // r = 0, c = 0
  // new line
* // r = 1, c = 0
  // new line
* // r = 2, c = 0
  // new line

Upvotes: 0

Daniel A. Thompson
Daniel A. Thompson

Reputation: 1924

break only breaks out of the innermost loop, not all loops. So the output is generated like so:

* // r = 0, c = 0
* // r = 1, c = 0
* // r = 2, c = 0

Upvotes: 1

Adi219
Adi219

Reputation: 4814

break literally breaks out of the innermost for loop.

It exits the loop it's in and the code continues as if the loop was finished.

Upvotes: 0

Related Questions