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