Remove white space at the end of the output in C

后端 未结 6 1292
离开以前
离开以前 2021-01-27 06:59

The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the online compiler against which I\'m checkin

6条回答
  •  无人及你
    2021-01-27 08:00

    the printf() statement,

     printf("%d ", a[k][i]);
    

    results in extra space. use

    "%d" without space or use space in the begining as,

    " %d"
    

    then at the end there wont be a extra space.
    its about how you use space in your printf(). use space in a way that extra space is not present at the end as you wanted.
    You can use code like this,

    while (k < m && l < n)
        {
            for (i = l; i < n; ++i)
            {
                if(l==0&&i==0)
                {
                  printf("%d", a[k][i]);
                }
                else
                  printf(" %d", a[k][i]);
            }
            k++;
            for (i = k; i < m; ++i)
                printf(" %d", a[i][n-1]);
            n--;
            if ( k < m)
            {
                for (i = n-1; i >= l; --i)
                    printf(" %d", a[m-1][i]);
                m--;
            }
            if (l < n)
            {
                for (i = m-1; i >= k; --i)
                    printf(" %d", a[i][l]);
                l++;
            }
    

提交回复
热议问题