Reputation: 113
My code has an error that prints the boxes on separate lines instead of inside of each other. I'm assuming that the problem lies with my initial for-loop; I am unsure how to adjust the algorithm. Any help would be greatly appreciated!
Here is what I need:
This is the code I currently have and its output:
#include <stdio.h>
int main(void) {
int boxes;
printf("How many boxes: ");
scanf("%d", &boxes);
int boxSide = boxes *3 + (boxes - 1);
int i;
int j;
for (i = 0, j = 0; i < boxes; i++, j += 2) {
int row = 1;
while (row <= boxSide) {
int column = 1;
while (column <= boxSide) {
if ( (row == (j+1) && column >= (j+1) && column <= boxSide - (j+1)) ||
(row == boxSide - j && column >= (j+1) && column <= boxSide - (j+1)) ||
(column == (j+1) && row >= (j+1) && row <= boxSide - (j+1)) ||
(column == boxSide - j && row >= (j+1) && row <= boxSide - j) ) {
printf("#");
}
else {
printf(" ");
}
column++;
}
row++;
printf("\n");
}
}
return 0;
}
Upvotes: 0
Views: 1826
Reputation: 8476
There are several ways to do it, some ideas:
1) Draw to an array, and when the drawing is ready, printf content of it:
char table[boxSide][boxSide];
...
if (...) {
table[x][y] = '#';
}
...
2) Move the boxes loop to the most inner loop:
while (row <= boxSide) {
while (column <= boxSide) {
char c = ' ';
for (i = 0, j = 0; i < boxes; i++, j += 2) {
if ( .... ) {
c = '#';
}
}
printf('%c', c);
...
Upvotes: 0
Reputation: 506
NCurses is your friend.
It has methods for printing things at specified locations.
Here is a tutorial that explains all of the methods, what NCurses is, and how to use it.
However, to answer your question...
This is happening because, unless you use a library like NCurses that has methods to move the cursor anywhere, println()
(or printf("\n")
) move the cursor to the next available line.
Upvotes: 3