Print repeating diamond shapes with custom rows, columns and length

Viewed 74

I am new to C, and I am trying to print diamond shapes according to the rows(2~10), columns(2~10) and the length(3, 5, 7, 9) of the diamond input from the user.

Using the code below I can print diamond and number of diamonds correctly, but I just can't get the correct distance between them.

void printDiamondWith(int diamondlength, int numberOfDiamonds) {

    int i, j, k;
    int star, space;

    star = 1;
    space = diamondlength;

    for (i = 1; i < diamondlength * 2 - 1; i++) {
        for (k = 0; k < numberOfDiamonds; k++) {
            for (j = 0; j < space; j++) {
                printf(" "); // Print the distance for the previous star
            }
            for (j = 1; j < star * 2; j++) {
                printf("*");
            }
            for (j = 0; j < space; j++) {
                printf(" "); // Print the distance for the next star
            }
        }
        printf("\n");

        // Check if length is equal 3, else length -1 to get the correct rows of second half of the diamond
        if (diamondlength == 3) {
            // Loops until the first half of the diamond is finished, then reverse the process to print the second half
            if(i < (diamondlength - diamondlength / 3)) {
                space--;
                star++;
            } else {
                space++;
                star--;
            }
        } else if (diamondlength >= 3) {
            if (i < (diamondlength - 1 - diamondlength / 3)) {
                space--;
                star++;
            } else {
                space++;
                star--;
            }
        }
    }
}

Actual running result:

actual result

Expected result:

Expected result

1 Answers

Your formulas for calculating the space is off. It works for me when I change this

space = diamondlength;

to this

space = diamondlength/2+1;

And this

for (k = 0; k < numberOfDiamonds; k++) {
    for (j = 0; j < space; j++) {

to this:

for (k = 0; k < numberOfDiamonds; k++) {
    for (j = 0; j < space-1; j++) {

In such situations I recommend hardcoding the variable for different parameters and write down what the variable has to be for what parameter so you can try to find a function that maps the parameter to the value. For instance I saw that as diamondlength increased, the space error also increased, so the relation between parameter and variable can't be one to one.

Related