whitespace - Remove white space at the end of the output in C -


the following code printing elements of matrix in spiral order. program works fine. problem, however, online compiler against i'm checking program, doesn't accept trailing white spaces @ end of output. give me ideas how can around last white space being added @ output?

for reference, code follows (yes variable names terrible. i'm working on changing habit of putting random variable names!!)

#include <stdio.h> int main() {     int a[6][6];     int i, k = 0, l = 0, m=3, n=3, j;     scanf("%d %d",&m, &n);     for(i=0;i<m;i++)     {         for(j=0;j<n;j++)             scanf("%d",&a[i][j]);     }     while (k < m && l < n)     {         (i = l; < n; ++i)             printf("%d ", a[k][i]);         k++;         (i = k; < m; ++i)             printf("%d ", a[i][n-1]);         n--;         if ( k < m)         {             (i = n-1; >= l; --i)                 printf("%d ", a[m-1][i]);             m--;         }         if (l < n)         {             (i = m-1; >= k; --i)                 printf("%d ", a[i][l]);             l++;         }     }     return 0; } 

input:

1 2 3  4 5 6  7 8 9 

output:

1 2 3 6 9 8 7 4 5{one space} 

any way fix problem? (also sorry terrible formatting. first question on stackoverflow!)

looking @ code, for (the first 1 in while loop):

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

will executed @ least ones (because l<n, coming while's condition).

then can following:

  • always add space in front of number
  • add single if check first for-loop (use bool flag).

for example, like:

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

this rather efficient , short solution - if in 1 loop , flag true once (will avoid cache misses).


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -