fork download
  1. // Online C++ compiler to run C++ program online
  2. #include <iostream>
  3. #include<bits/stdc++.h>
  4. #include <iomanip>
  5. using namespace std;
  6. int main() {
  7. int n;
  8. std::cout << "Enter the value of n: ";
  9. cin >> n;
  10.  
  11. vector<vector<int>> matrix(n, vector<int>(n, 0));
  12.  
  13. int num = 1,start=0,j=0;
  14. int limit=(n-1)/2;
  15. bool check=false;
  16. int per_row=(n-1)/2;
  17. if(n%2==1){
  18. limit=2;
  19. check=false;
  20. per_row=2;
  21. }else{
  22. limit=2;
  23. check=true;
  24. per_row=1;
  25. }
  26.  
  27. for (int i = n - 1; i >= 0; i--) {
  28. check=!check;
  29.  
  30. if(check){
  31. j=n-1;
  32. }else{
  33. j=start;
  34. }
  35. while(true) {
  36. if(j<start||j==n)break;
  37. if(check){
  38. matrix[i][j]=num++;
  39. j--;
  40. }else{
  41. matrix[i][j]=num++;
  42. j++;
  43. }
  44. }
  45. if(per_row==limit){
  46. start+=2;
  47. per_row=0;
  48. }
  49. per_row++;
  50. if(start>=n)break;
  51. }
  52.  
  53. for (int i = 0; i < n; i++) {
  54. for (int j = 0; j < n; j++) {
  55. if (matrix[i][j] == 0)
  56. std::cout << std::setw(3) << " " << "\t";
  57. else
  58. std::cout << std::setw(3) << matrix[i][j] << "\t";
  59. }
  60. std::cout << std::endl;
  61. }
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0.01s 5548KB
stdin
4
stdout
Enter the value of n:    	   	 12	 11	
   	   	  9	 10	
  8	  7	  6	  5	
  1	  2	  3	  4