fork(29) download
  1. #include<iostream>
  2. #define R 4
  3. #define C 4
  4. using namespace std;
  5. int main()
  6. {
  7.  
  8. int mat[][C]={
  9. {1,2,3,4},
  10. {5,6,7,8},
  11. {9,10,11,12},
  12. {13,14,15,16}
  13. };
  14.  
  15. int top=0;
  16. int down=R-1;
  17. int left=0;
  18. int right=C-1;
  19.  
  20. while(true)
  21. {
  22.  
  23. //print first row
  24. for(int i=left;i<=right;++i) cout<<mat[top][i]<<" ";
  25. top++;
  26.  
  27. if(top>down || left>right) break;
  28. //print last column
  29. for(int i=top;i<=down;++i) cout<<mat[i][right]<<" ";
  30. right--;
  31.  
  32. if(top>down || left>right) break;
  33. //print last row
  34. for(int i=right;i>=left;--i) cout<<mat[down][i]<<" ";
  35. down--;
  36.  
  37. if(top>down || left>right) break;
  38. //print first column
  39. for(int i=down;i>=top;--i) cout<<mat[i][left]<<" ";
  40. left++;
  41. if(top>down || left>right) break;
  42. }
  43. return 0;
  44. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10