Reputation: 283
I'm working on a program that prints a Sierpinski triangle based on a user input of height and fractal level. Here is what my program should produce with an input of height 8 and fractal level 1:
*
***
*****
*******
* *
*** ***
***** *****
******* *******
This is what I have so far:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char *argv[]) {
int height, draw, errno, fractal_level;
char *p;
char *q;
errno = 0;
height = strtol(argv[1], &p, 10);
fractal_level = strtol(argv[2],&q, 10);
if (errno != 0 || p == argv[1]) {
printf("ERROR: Height must be integer.\n");
exit(1);
}
else if (errno != 0 || q == argv[2]) {
printf("ERROR: Fractal Level must be integer.\n");
exit(1);
}
int x,y;
x=(2*height-1) / 2;
y=(2*height-1) / 2;
printf("x: %d y: %d \n", x, y);
drawSier(height, fractal_level, x, y);
return 0;
}
int drawSier(height, fractal_level, x, y) {
//If the fractal level is zero, it's just a normal triangle.
if (fractal_level==0)
{
drawTriangle(height, x, y);
}
//the function calls itself, but with a slight variance
//in the starting point of the triangle, for the top, bottom left, and bottom right
else {
//top
drawSier(height/2, fractal_level-1, x, y);
//bottom left
drawSier(height/2, fractal_level-1, x-height/2, y-height/2);
//bottom right
drawSier(height/2, fractal_level-1, x+height/2, y-height/2);
}
}
int drawTriangle(height, x, y){
if (height<1) {
printf("ERROR: Height too small.\n");
exit(1);
}
else if (height>129) {
printf("ERROR: Height too large.\n");
exit(1);
}
for (int i = 1; i <= height; i++)
{
int draw=0;
// this 'for' loop will take care of printing the blank spaces
for (int j = i; j <= x; j++)
{
printf(" ");
}
//This while loop actually prints the "*"s of the triangle by multiplying the counter
//by 2R-1, in order to output the correct pattern of stars. This is done AFTER the for
//loop that prints the spaces, and all of this is contained in the larger 'for' loop.
while(draw!=2*i-1) {
printf("*");
draw++;
}
draw=0;
//We print a new line and start the loop again
printf("\n");
}
return 0;
}
Here is what my program is currently producing with the same input:
*
***
*****
*******
*
***
*****
*******
*
***
*****
*******
I'm not sure what's going wrong. It seems to be an issue with the y variable.
Upvotes: 1
Views: 882
Reputation: 229593
y
is passed to drawTriangle()
but the function doesn't use it. It just prints new lines with the triangle, below the things printed previously.
You can either use console control codes to move the cursor around to the desired position before printing (taking care to not overwrite previously printed output), or you can create the full image in memory first and only print it out in the end.
Upvotes: 1