Printing Pattern Using Loops

  • + 0 comments

    Hmmm, IMHO the tests suit machinery use to validate output (in the assert stage), could be improved using patterns, to discard whites character, specially if we use format string to justify the out put it fails.

    printf ("%5d", np);

    #include <stdio.h>
    
    /**
     * Given @param n as natural number it prints the following pattern:
     *
     *   |---------  2n - 1 ----------|         ^
     *   
     *    n    n    n   ...     n    n          |
     *    n   n-1  n-1  ...   n-1    n          |
     *    n  n-1  n-2 ...  n-2  n-1  n          |
     *    ...			          
     *    n n-1 n-2 .. 1 .. n-2 n-1  n        2n - 1
     *    ...			          
     *    n  n-1  n-2 ...  n-2  n-1  n          |
     *    ...                                   |
     *    n  n-1  n-1  ...   n-1     n          |
     *    n    n    n   ...     n    n          v
     * 
     * Please note that dimession of "square" is giving by the expression: `2n - 1'.
     *
     * I used a Cartesian coordinates to know which number will be located at which
     * position, incrementing or decrement in function of the coordinate (r,c).
     */
    void
    print_pattern (int n)
    {
      int r, c;
      
      if (n <= 0)
        {
          fprintf (stderr, "%s: error: invalid parameter\n", __func__);
          return;
        }
    
      for (r = 0; r < 2 * n - 1; ++r)
        {
          int np = n;
    
          for (c = 0; c < 2 * n - 1; ++c)
            {
              printf ("%5d", np);
    	  
    	  if (c < r)
                np--;
    	  if (c + r >= 2 * n - 2)
                np++;
            }
    
          puts ("");
        }
    }
    
    int
    main ()
    {
      int n;
    
      if (scanf ("%d", &n) != 1)
        {
          fprintf (stderr, "error: invalid input\n");
          return 1;
        }
    
      print_pattern (n);
    
      return 0;
    }