Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

draw - 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("
");
    }
}
question from:https://stackoverflow.com/questions/66051243/drawing-a-numbered-triangle-in-c-using-loops

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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("
");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...