notme121
notme121

Reputation: 11

Pyramid patterns using C

I need to do the following pattern using do-while, while or for.

enter image description here

I tried the following code but it prints the pattern only 1-5 I also tried to alter the n being 10 but then the spacing goes nuts.

#include <stdio.h>
int main(void)
{
  int n = 5, i, j, num = 1, gap;


  gap = n - 1;

  for ( j = 1 ; j <= n ; j++ )
  {
      num = j;

      for ( i = 1 ; i <= gap ; i++ )
          printf(" ");

      gap --;

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

  }

  return 0;
}

Upvotes: 1

Views: 522

Answers (1)

tstanisl
tstanisl

Reputation: 14127

Try replacing both occurences of:

printf("%d", num);

with

printf("%d", num % 10);

Now only the last digit will be shown.

After the change, for n set to 10 the program produces:

         1
        232
       34543
      4567654
     567898765
    67890109876
   7890123210987
  890123454321098
 90123456765432109
0123456789876543210

Upvotes: 5

Related Questions