Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. const int n = 5;
  4. int main()
  5. {
  6.  
  7. int arr[n][n];
  8. int len = n, k = 1, p = 0, i; /*k is to assign the values to the array from 1...n*n */
  9. /*len is used to update(decrease) array size so that values cans be assign to them */
  10. while (k <= n * n)
  11. {
  12. for (i = p; i < len; i++) /*Loop to access the first row of the array*/
  13. {
  14. arr[p][i] = k++;
  15. }
  16. for (i = p + 1; i < len; i++) /*Loop tp access the last column of the array*/
  17. {
  18. arr[i][len - 1] = k++;
  19. }
  20. for (i = len - 2; i >= p; i--) /*Loop to access the last row of the array*/
  21. {
  22. arr[len - 1][i] = k++;
  23. }
  24. for (i = len - 2; i > p; i--) /*Loop to access the first column of the array*/
  25. {
  26. arr[i][p] = k++;
  27. }
  28. p++, len = len - 1;
  29.  
  30. }
  31. if (n % 2) /*This block will run only if n is even*/
  32. {
  33. arr[(n + 1) / 2][(n + 1) / 2] = n * n; /*It will assign the last value to the centremost element*/
  34. }
  35. for (i = 0; i < n; i++) /*This loop will print the array in matrix format*/
  36. {
  37. for (int j = 0; j < n; j++)
  38. {
  39. cout << arr[i][j] << "\t";
  40. }
  41. cout << endl;
  42. }
  43. return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement