Search code examples
cfor-loopprintfnested-loops

C program for a reverse triangle pattern


I want to draw a pattern like this:

567898765
 4567654
  34543
   232
    1

But I can't seem to figure it out, because this is the output I'm currently getting:

567898765
 45678987654
  3456789876543
   234567898765432
    12345678987654321

This is my code:

#include <stdio.h>

int main() {
  int a, b, c, s;
  for (a = 5; a >= 1; a--) {
    for (s = a; s <= 4; s++) {
      printf(" ");
    }
    for (b = a; b <= 9; b++) {
      printf("%d", b);
    }
    for (c = 8; c >= a; c--) {
      printf("%d", c);
    }
    printf("\n");
  }
  return 0;
}

Solution

  • You got it mostly right, only the constant values 9 and 8 in the b and c loops are inappropriate, since the triangle's central axis isn't always 9; the values are 2*a-1 and 2*a-2, respectively.