简体   繁体   中英

Problem while handling strings in C(Printing them)

this is the first question I am gonna ask.

So this is just a coding problem where (n,m) is given and you have to print zig-zag pattern.

The Program is fairly simple but somehow I have problem understanding strings and character arrays. I cannot understand what is going on and why the program printing beyond the value of m

Eg.

Input: 9 9
Output:

#########
........#
#########
#........
#########
........#
#########
#........
#########

//(☞゚ヮ゚)☞NOTSOAWESOME 
#include<stdio.h>
#include<string.h>
int main()
{
   int n,m,i;
   scanf("%d %d",&n,&m);
   char snake[m],right[m],left[m];
   for(i=0;i<m;i++)
   {
       snake[i]='#';
       right[i]='.';
       left[i]='.';
   }
   left[0]='#';
   right[m-1]='#';
   for(i=0;i<n;i++)
   {
       if(i%2==0)printf("%s\n",snake);
       else if((i-1)%4==0)printf("%s\n",right);
       else if((i-3)%4==0)printf("%s\n",left);
   }
}

My output for the above Input is,
#########@
........#g�@�
#########@
#........�Q�
#########@
........#g�@�
#########@
#........�Q�
#########@

I avoid it because that would be nested loops and a bit messy.

I agree it requires an inner loop but it does save on space, which may not matter on this particular problem but could in other situations.

A partially tested solution avoiding extra storage is attempted below.

#include <stdio.h>

enum LINE_STATE {
    LEFT = 0,
    RIGHT,
    SNAKE,
    MAX_STATE,
};

int main()
{
    int n, m, i, j;
    enum LINE_STATE s = SNAKE, prev = RIGHT;

    scanf("%d %d",&n,&m);

    for (i = 1; i <= n; i++) {
           printf("%c", (s == SNAKE || s == LEFT) ? '#' : '.');
           for (j = 1; j < m - 1; j++)
                printf("%c", s == SNAKE ? '#' : '.');
           printf("%c\n", (s == SNAKE || s == RIGHT) ? '#' : '.');
           if (i % 2) {
               s = (prev + 1) % 2; // next line is even-numbered, alternate between LEFT and RIGHT
           } else {
               prev = s;
               s = SNAKE;  // next line is an odd-numbered, only SNAKE
           }
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM