This blog is under construction

Saturday 22 June 2013

C program to print triangle of numbers - I

Write a C program to print given triangle of numbers.

              1  2  3  4  5  6  7
                  1  2  3  4  5
                      1  2  3
                          1



  #include <stdio.h>
  int main () {
        int i, j, k, n, temp;
        printf("Enter the value for n:");
        scanf("%d", &n);
        temp = n + 3;
        for (i = 1; i <= n; i++) {
                /* space before triangle's start */
                for (j = 1; j <= n; j++)
                        printf("   ");

                /* space at the front half of triangle */
                for (j = 1; j < i; j++)
                        printf("   ");

                /* print value */
                for (k = 1; k <= temp; k++)
                        printf("%3d", k);

                printf("\n");
                temp = temp - 2;
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:4
              1  2  3  4  5  6  7
                  1  2  3  4  5
                      1  2  3
                          1



No comments:

Post a Comment