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