Printing out characters in an X pattern using for loops

纵饮孤独 提交于 2019-12-01 23:11:56

For a little bit of fun:

int main (void)
{
    int i;
    int w = 7;
    for (i=1;i<=w*(w+1);i++)
        printf (
            "%c",
            i % (w+1) == 0 ? '\n' : 
            i % (w) == 0 || i % (w+2) == 1 ? '*' : ' ');

}

A slight extension to one of the good solutions above for the cross ended up being a bit more than just crossing x's:

#include <stdio.h>

int main(){
    int n = 4 - 1;
    char ch[] = "x";
    int i = 0, dx = 1;

    printf ("\n  __\n  ||----------------------------\n");
    do {
        printf ("  %s %*s%*.*s %*c\n", "||", 4*i+1, ch, 8*(n-i), 8*(n-i), ch, 4*i+1, '|');
        if ((i += dx)==n)
            dx = -dx;
    } while (i>=0);
    printf ("  ||----------------------------\n");
    for (i = 0; i < 10; i++)
        printf ("  ||\n");
    printf ("------\n\n");

    return 0;
}

output:

$ ./bin/flag

  __
  ||----------------------------
  || x                       x |
  ||     x               x     |
  ||         x       x         |
  ||             x             |
  ||         x       x         |
  ||     x               x     |
  || x                       x |
  ||----------------------------
  ||
  ||
  ||
  ||
  ||
  ||
  ||
  ||
  ||
  ||
------
#include <stdio.h>

int main(){
    int n = 5 - 1;
    char ch[] = "x";
    int i = 0, dx = 1;

    do{
        printf("%*s%*.*s\n", i+1, ch, 2*(n-i),2*(n-i), ch);
        if((i += dx)==n)
            dx = -dx;
    }while(i>=0);
    return 0;
}

for(;;){
    printf("%*s%*.*s\n", i+1, ch, 2*(n-i),2*(n-i), ch);
    if((i += dx)==n)
        dx = -dx;
    else if(i < 0)
        break;
}

int n = 5 - 1;
char ch[] = "x";
int i = 0;

for(; i < n ; ++i){
    printf("%*s%*.*s\n", i+1, ch, 2*(n-i),2*(n-i), ch);
}
for(; i >=0 ; --i){
    printf("%*s%*.*s\n", i+1, ch, 2*(n-i),2*(n-i), ch);
}

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

#include <stdio.h>
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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!