Hope you all know about spiral matrices. Here the given c++ program will gives spiral matrix as output. This is commonly asked in programming rounds of many interviews.
input : 4;
output is :
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
input : 5;
output :
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
This is one of the method for creating spiral matrix. This may not be an efficient method you can also search for others methods.
input : 4;
output is :
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
input : 5;
output :
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
#include <iostream> #include <iomanip> #define SIZE 4 int main() { int matrix[SIZE][SIZE] = {0}; int count = 0; int up = 0; int down = SIZE - 1; while(count != SIZE * SIZE) { for(int i = 0; i < SIZE; ++i) { if(matrix[up][i] == 0) { matrix[up][i] = ++count; } } for(int i = 0; i < SIZE; ++i) { if(matrix[i][down] == 0) { matrix[i][down] = ++count; } } for(int i = SIZE - 1; i >= 0; --i) { if(matrix[down][i] == 0) { matrix[down][i] = ++count; } } for(int i = SIZE - 1; i >= 0; --i) { if(matrix[i][up] == 0) { matrix[i][up] = ++count; } } ++up; --down; } std::cout << "The Spiral Matrix of number : " << SIZE << std::endl; for(int i = 0; i < SIZE; ++i) { for(int j = 0; j < SIZE; ++j) { std::cout << std::setw(4) << matrix[i][j] << " "; } std::cout << std::endl; } }
This is one of the method for creating spiral matrix. This may not be an efficient method you can also search for others methods.