Any one can help me out i want to display a spiral of n*n size with out using arrays?

``````out put when n=2 should be 3 2
0 1
when n=3 should be 8 7 6
1 0 5
2 3 4

when n=4 should be 15 14 13 12
04 03 02 11
05 00 01 10
06 07 08 09
``````

Something like this?

``````#include <stdio.h>
#include <assert.h>

void DrawSpiralLine(const int n, const int line)
{
// Throw an assertion when faulty parameters are supplied.
assert(line >= 0 && line < n && n > 0);

const int square = n * n;
int       i      = 0;

// …``````

## All 7 Replies

Something like this?

``````#include <stdio.h>
#include <assert.h>

void DrawSpiralLine(const int n, const int line)
{
// Throw an assertion when faulty parameters are supplied.
assert(line >= 0 && line < n && n > 0);

const int square = n * n;
int       i      = 0;

// Simple case: The first line of a spiral.
if (line == 0)
{
for (i = 0; i < n; i++)
{
printf("%02d ", (square - 1) - i);
}
}

// Simple case: The last line of a spiral.
else if (line == (n - 1))
{
for (i = 0; i < n; i++)
{
printf("%02d ", square - (3 * n) + 2 + i);
}
}

// Complex case: Line with other inner spirals.
else
{
// Print the first character.
printf("%02d ", square - (4 * n) + 4 + (line - 1));

// Print a line of the rest
DrawSpiralLine(n - 2, line - 1);

// Print the last character
printf("%02d ", (square - 1) - n - (line - 1));
}
}

void DrawSpiral(const int n)
{
int i = 0;

// Draw the lines of the spiral.
for (i = 0; i < n; i++)
{
DrawSpiralLine(n, i);
printf("\n");
}
}

int main(void)
{
DrawSpiral(6);
return 0;
}
``````

DrawSpiral(6) will draw something like:

``````35 34 33 32 31 30
16 15 14 13 12 29
17 04 03 02 11 28
18 05 00 01 10 27
19 06 07 08 09 26
20 21 22 23 24 25
``````

Let me know if there's anything specific you want to know, I think it's pretty straight forward. (Recursive solutions are often pretty easy to read)

how you arange output ???
i mean why 8 print as fist element in output when n=2
?????????????????

if you use console screen
you can use gotoxy() function to draw output

you can use gotoxy() function to draw output

gotoxy() isn't widely implemented by compilers. You're essentially assuming that the OP is using Turbo C, which isn't a safe assumption.

yes i know
so that i telod to him

if you use console screen

The "console screen" isn't unique to Turbo C. Your suggestion is still very poor and makes unwarranted assumptions about the OP's compiler and operating system.

you are right

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.