Search code examples
c++nested-loops

(C++) How to imagine working of nested loops?


I have no idea what's going on how to imagine that, one more thing like in 3rd for loop there's a condition that k<j but its upper loop j is set to 0 and i is also 0 then as I think k=0 if this is right than 0<0 how's that can be valid????

void printing_subarrays(int *arr,int n){
for(int i=0; i<n; i++){
    for(int j=0; j<n; j++){
        for(int k=i; k<j; k++){
            cout<<arr[k]<<", ";
        }cout<<endl;
    }cout<<endl;
}

}


Solution

  • I don't think it makes much sense for us to explain what's happening, you need to see it for yourself.
    Therefore I've added some output lines, which will show you how the values of the variables i, j and k evolve through the loops:

    for(int i=0; i<n; i++){
        cout<<"i=["<<i<<"]"<<endl;
        for(int j=0; j<n; j++){
            cout<<"i=["<<i<<"], j=["<<j<<"]"<<endl;
            for(int k=i; k<j; k++){
                cout<<"i=["<<i<<"], j=["<<j<<"], k=["<<k<<"]"<<endl;
                cout<<arr[k]<<", ";
            }
            cout<<endl;
        }
        cout<<endl;
    }