Click here to Skip to main content
16,020,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I try to make a spiral, that reads odd number from the input (from 1 to 15), and it will draw a spiral from "#" and "." characters on the output. For example
input:
7


output:
#######
......#
#####.#
#...#.#
#.###.#
#.....#
#######


or

intput:
9


output:
#########
........#
#######.#
#.....#.#
#.###.#.#
#.#...#.#
#.#####.#
#.......#
#########


What I have tried:

Yesterday I tried to make a cover of the spiral - succesfully -
Today I got stuck. It works for inputs: 1,3,5,7,9 and 11. But it doesn´t work for 13 and 15.


#include<stdio.h>
 
int main(){
	int n;
	scanf("%d",&n);
	fflush(stdin);
 
	for(int i = 0;i<n;i++){
		for(int j = 0;j<n;j++){
			if(i==0||i==n-1||j==n-1)
				printf("#");
			else if(j==0&&i>1&&i<n-1)
				printf("#");
			else if(i==2&&j<n-2)
				printf("#");
			else if(j==n-3&&i>2&&i<n-2)
				printf("#");
			else if(i==n-3&&j<n-3&&j>1)
				printf("#");
			else if(j==2&&i>3&&i<n-2)
				printf("#");
			else if(i==4&&j>2&&j<n-4)
				printf("#");
			else if(j==6&&i>4&&i<n-4)
				printf("#");
			else if(i==6&&j>3&&j<n-5)
				printf("#");
			else printf(".");
			
		}
		printf("\n");
	}
	getchar();
	return 0;
 
}
Posted
Comments
Rick York 26-Dec-17 16:12pm    
You need to refine your logic checks because they will fail at higher values too.

I would revise the logic to add a variable called size or length or something similar and set it initially to the size of the spiral. Then as you complete each 'revolution' of the spiral decrement the size. Continue looping until size is too small to make a full loop. The loops are essentially the same for every revolution but they get smaller each time so figure out how to do one loop, and then how much it shrinks each time and you will have it. It should work for any size if you do the loop correctly.

1 solution

Quote:
It works for inputs: 1,3,5,7,9 and 11. But it doesn´t work for 13 and 15.

You are on the wrong way. Once you fixed the code for 13 and 15, you will have to fix it for 17 and 19. And the main reason why it don't work for even numbers is that your code do not handle it.

There is another way which will handle even and odd numbers at once.
Build a 2D array of chars.
Fill the array with '.'
Set square limits 0,0 and n-1,n-1
Loop as long as spiral is not finished
    Draw outer loop of spiral in order (use 1 loop per line)
    Reduce square
Print 2D array
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900