This blog is under construction

Friday 12 July 2013

C program to generate pyramid of numbers

Write a C program to generate a pyramid of numbers.


  #include <stdio.h>

  int main() {
        int n, i, j, k, num = 1;

        /* get the input value n from the user */
        printf("Enter the value for n(1-10):");
        scanf("%d", &n);

        /* boundary check */
        if (n < 1 || n > 10) {
                printf("Boundary Value Exceeded!!\n");
        }

        /* construct pyramid */
        for (i = 1; i <= n; i++) {
                printf("    ");
                /* space infront of pyramid */
                for (j = i; j < n; j++) {
                        printf("  ");
                }

                /* builds first vertical half of pyramid */
                for (k = 1; k <= i; k++) {
                        /* valid num values are 1-9 */
                        if (num > 9)
                                num = 1;
                        printf("%d ", num++);
                }

                /* builds next half of pyramid */
                for (k = 1; k < i; k++) {
                        /* valid num values are 1-9 */
                        if (num > 9)
                                num = 1;
                        printf("%d ", num++);
                }

                /* moves cursor to new line */
                printf("\n");
        }
        return 0;
  }



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



No comments:

Post a Comment