This blog is under construction

Wednesday 10 July 2013

C program to print star diamond pattern

Write a C program to print star diamond pattern.


  #include <stdio.h>

  int main() {
        int n, i, j, k;

        /* 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("\t");
                /* space infront of + */
                for (j = i; j < n; j++) {
                        printf("  ");
                }

                /* builds first vertical half of pyramid */
                for (k = 1; k <= i; k++) {
                        printf("+ ");
                }

                /* builds next half of pyramid */
                for (k = 1; k < i; k++) {
                        printf("+ ");
                }

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

        /* construct inverted pyramid to get diamond shape */
        for (i = n - 1; i >= 1; i--) {
                printf("\t");
                for (j = i; j < n; j++) {
                        printf("  ");
                }

                /* builds first vertical half of pyramid */
                for (k = 1; k <= i; k++) {
                        printf("+ ");
                }

                /* builds next half of pyramid */
                for (k = 1; k < i; k++) {
                        printf("+ ");
                }

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



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n(1-10):5
            + 
          + + + 
       + + + + + 
       + + + + + + + 
 + + + + + + + + + 
    + + + + + + + 
       + + + + + 
         + + + 
           + 




No comments:

Post a Comment