Printing out characters in an X pattern using for loops

后端 未结 4 1315
小蘑菇
小蘑菇 2021-01-21 14:05

I\'m trying to print this big X pattern:

 x       x
  x     x
   x   x
    x x
     x
    x x
   x   x
  x     x
 x       x

I can\'t figure out

4条回答
  •  甜味超标
    2021-01-21 14:45

    Here's your program with minimum modifications to do what you want:

    #include 
    int main()
    {
      int j,i;
      char ch[] = "x";               // (1)
      int sz = 8;                    // (2)
      for( j = sz; j >= 0 ; --j)
        {
          for(i = sz; i>=0; --i)
            {
              if(sz-j == i || i == j)// (3) 
              {
                 printf("%s",ch);
              } else {
                 printf(" ");        // (4)
              }
            }
          printf("\n");
        }
      return 0;
    }
    

    Explanation:

    (1) First of all, if you want x, you should print x :)

    (2) Use a variable for the size, so you can play with it ...

    (3) You have to print two x per line, i.e. in two positions in the inner loop.

    These positions lie on the two diagonals where either x == y (here i == j), or x == 8 - y (here i == sz -j)

    (4) You have to print a space otherwise

    See here: https://eval.in/228155

提交回复
热议问题