Home > Mobile >  How to successfully take a step back and preserve the shape? C programming - loops
How to successfully take a step back and preserve the shape? C programming - loops

Time:12-12

I wrote this code, but I have one error that I can't fix, the problem is that the code works well but actually what my program prints to the number n: 3 should be to n: 2 you can see it in the picture. when 5 is actually 4 etc... When I fix the loops I move the look of the lines and then it's no longer a diamond.

enter image description here

#include <stdio.h>
 
int main() {
    int i, j, n;
 
    printf("n: ");
    scanf("%d", &n);
    for (j = 1; j < n; j  ) { 
        printf(" ");
    }
    printf(" ");
 
    printf(" \n");
    for (i = 2; i < n; i  ) {
        for (j = 1; j <= n - 1; j  ) { 
            if ((i   j) == (n   1))
                printf("/");     
            else
                printf(" ");      
        }
        for (j = 1; j < n; j  ) { 
            if (i == j)         
                printf("\\");    
            else
                printf(" ");     
        }
        printf("\n");
    }

    for (i = 2; i < n; i  ) {
        for (j = 1; j < n; j  ) { 
            if (i == j)           
                printf("\\");    
            else
                printf(" ");      
        }
        for (j = 1; j <= n - 1; j  ) { 
            if ((i   j) == (n   1))
                printf("/");     
            else
                printf(" ");      
        }
        printf("\n");
    }
    for (j = 1; j < n; j  ) { 
        printf(" ");
    }
    printf(" ");
    return 0;
}

CodePudding user response:

It seems that just adding 1 to n would solve your problem.

CodePudding user response:

A quick and dirty fix is adding 1 to n after the scanf("%d", &n);

Here is a modified version taking advantage of the printf width feature:

#include <stdio.h>

int main() {
    int i, n;

    printf("n: ");
    if (scanf("%d", &n) != 1)
        return 1;

    printf("%*s\n", n, " ");
    for (i = 1; i < n; i  ) {
        printf("%*s%*s\n", n - i, "/", i * 2, "\\");
    }
    for (i = 1; i < n; i  ) {
        printf("%*s%*s\n", i, "\\", (n - i) * 2, "/");
    }
    printf("%*s\n", n, " ");
    return 0;
}
  • Related