Search code examples
cdrawshapestriangle

Drawing a numbered triangle in c using loops


I'm working on the first 2 parts (the ascending numbers and the spaces) Original

this is how it's supposed to look like:

1 2 3 4 5 4 3 2 1
  2 3 4 5 4 3 2
    3 4 5 4 3
      4 5 4
        5

My code is:

#include <stdio.h>

main()
{
    int N, i, j, M;

    do {
        printf("Entrez la valeur de N : ");
        scanf("%d", &N);
    } while (N <= 0 || N % 2 == 0);

    M = N;

    for (N = N; N >= 0; N--) {
        for (i = M; M - N > 0; i--)
            printf(" ");
        for (j = 1; j <= N; j++) {
            printf(" %d ", j);
        }
        printf("\n");
    }
}

Solution

  • Your main issue is that the names of your variables introduce confusion.

    In particular here, for (i = M; M - N > 0; i--) the condition M-N > 0 introduces an infinite loop.

    Everything becomes much simpler with better names selection.

    Output

    Entrez la valeur de N : 5
     1 2 3 4 5 4 3 2 1
       2 3 4 5 4 3 2
         3 4 5 4 3
           4 5 4
             5
    
    #include <stdio.h>
    
    int main() {
        int N;
    
        do {
            printf("Entrez la valeur de N : ");
            scanf("%d", &N);
        } while (N <= 0 || N % 2 == 0);
    
        for (int row = 1; row <= N; ++row) {
            int n_blank = 2 * (row - 1);
            for (int i = 0; i < n_blank; ++i)
                printf(" ");
            for (int j = row; j <= N; j++) {
                printf(" %d", j);
            }
            for (int j = N-1; j >= row; j--) {
                printf(" %d", j);
            }
            printf("\n");
        }
    }