A c program to fill an N x N two-dimensional array, in a circular (Spiral) pattern. The numbers to be filled increments by 1.
#include <iostream>
#define R 3
#define C 6
void spiralFill(int m, int n, int a[R][C])
{
int i, k = 0, l = 0;
int x = 0;
while (k < m && l < n) {
for (i = l; i < n; ++i) {
a[k][i] = x++;
}
k++;
for (i = k; i < m; ++i) {
a[i][n - 1] = x++;
}
n--;
if (k < m) {
for (i = n - 1; i >= l; --i) {
a[m - 1][i] = x++;
}
m--;
}
if (l < n) {
for (i = m - 1; i >= k; --i) {
a[i][l] = x++;
}
l++;
}
}
}
void print(int a[R][C])
{
for (int i = 0; i != R; ++i)
{
for (int j = 0; j != C; ++j)
{
std::cout << a[i][j] << '\t';
}
std::cout << std::endl;
}
}
int main()
{
int a[R][C] = { { 1, 2, 3, 4, 5, 6 },
{ 7, 8, 9, 10, 11, 12 },
{ 13, 14, 15, 16, 17, 18 } };
spiralFill(R, C, a);
print(a);
return 0;
}
Comments
Leave a comment