Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created December 1, 2012 17:45
Show Gist options
  • Select an option

  • Save alexesDev/4183508 to your computer and use it in GitHub Desktop.

Select an option

Save alexesDev/4183508 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
int size = 0;
int x, y, step;
int value = 0;
int stepCount = 0;
int *matrix;
//size = 10;
printf("Enter size: ");
scanf("%d", &size);
printf("\n");
value = size * size;
stepCount = size / 2;
matrix = (int*)malloc(size * size * sizeof(int));
// main part
for(step = 0; step < stepCount; ++step)
{
//top side
for(y = 0 + step; y < size - step; ++y)
matrix[(0 + step) * size + y] = value--;
//right side
for(x = 1 + step; x < size - step; ++x)
matrix[(x * size) + size - 1 - step] = value--;
//bottom side
for(y = size - 2 - step; y >= 0 + step; --y)
matrix[(size - 1 - step) * size + y] = value--;
//left size
for(x = size - 2 - step; x > 0 + step; --x)
matrix[(x * size) + 0 + step] = value--;
}
if(size % 2 == 1)
matrix[stepCount * size + stepCount] = 1;
// end main part
for(x = 0; x < size; ++x, printf("\n"))
for(y = 0; y < size; ++y)
printf("%3d ", matrix[x * size + y]);
free(matrix);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment