Remove white space at the end of the output in C

后端 未结 6 1309
离开以前
离开以前 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 07:55

    Looking at your code, this for (the first one in the while loop):

    for (i = l; i < n; ++i)
        printf("%d ", a[k][i]);
    

    will always be executed at least ones (because l, coming from the while's condition).

    Then you can just do the following:

    • always add the space in front of the number
    • add a single if check just for this very first for-loop (use some bool flag).

    For example, something like:

    bool first = true;
    while (k < m && l < n)
    {
        for (i = l; i < n; ++i)
        {
            if( ! first )
            {
                printf(" %d", a[k][i]);
            }
            else
            {
                printf("%d", a[k][i]);
                first = false;
            }
        }
        // ....
    }
    

    This will be rather efficient and short solution - the if is in just one loop and the flag will be true just once (will avoid cache misses).

提交回复
热议问题