0

Ok so i was working on some programs given in my text book which is

{
    int n,k;
    n=1;
    while(n<=5){
        cout<<"\n";
        for(k=1;k<=n;k++)
        
        
        cout<<k<<" ";
        n++;
    
    }

}

the output isenter image description here but after that when i added braces in for loop it burst

 {
    int n,k;
    n=1;
    while(n<=5){
        cout<<"\n";
        for(k=1;k<=n;k++){
        
        
        cout<<k<<" ";
        n++;}
    
    }

}

enter image description here SO can anyone explain why this happen's?

meeeeeeee
  • 1
  • 2
  • 5
    C++ is not Python. Indentation doesn't mean anything in C++. If you want two or more lines of code to be influenced by the `for` loop, then braces are required. Braces are how you do block scope in C++. – PaulMcKenzie Mar 04 '21 at 15:45
  • 1
    Indentation does nothing in C++ except make the code easier to read. In C++, scopes are controlled by curly braces. – NathanOliver Mar 04 '21 at 15:46
  • 3
    If you increase `n`and `k`at the same time, you will always have `k <= n`, and the loop will never finish. – Damien Mar 04 '21 at 15:46

1 Answers1

0

The (simplified) grammar of a for loop is following:

for (init ; condition ; iteration) statement

Notice that the loop body consists of a single statement. In the first example, that statement is the expression statement

cout<<k<<" ";

In the second example, that statement is the block statement

{
    
    
    cout<<k<<" ";
    n++;}

}

This block statement contains more than one expression statement.

eerorika
  • 232,697
  • 12
  • 197
  • 326