Why my code is printing wrong output for 4*2 matrix

class Solution {
public:
vector spiralOrder(vector<vector>& arr) {
vector res;

    int r = arr.size();
    int c = arr[0].size();
    int sr =0, sc =0, er =r-1, ec=c-1;
    while(sr<=er && sc<=ec){
        for(int i= sc; i<=ec; i++){
            res.push_back(arr[sr][i]);
        }
        sr++;
        for(int i=sr; i<=er; i++ ){
           res.push_back(arr[i][ec]);
        }
        ec--;
        if(sr<er){
            for(int i= ec; i>=sc; i--){
               res.push_back(arr[er][i]);
            }
            er--;
        }
        if(sc<ec){
            for(int i =er; i>=sr; i--){
                res.push_back(arr[i][sc]);
            }
            sc++;
        }
    } 
    return res;
}

};

int main() {
vector<vector> nums = {{1,2,3,4},
{4,5,6,7},
// {8,9,10,11},
// {12,13,14,15}
};
vector n = spiralOrder(nums);
for( auto i : n){
cout<<i<<" ";
}
return 0;
}

input : vector<vector> nums = {{1,2,3,4},
{4,5,6,7}}
output: 1 2 3 4 7 4 5 6
desired output: [1,2,3,4,8,7,6,5]

hi @discobot share code on ide.codingblocks.com
write
save (ctrl + s)
send the url of the page

Hi! To find out what I can do, say @discobot display help.

I can’t see the url of the solution. Can you please share it again.

Hi @discobot https://ide.codingblocks.com/s/658992

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.