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 checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?
For reference, my code is as follows (yes the variable names are terrible. I'm working on changing my 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)
{
for (i = l; i < n; ++i)
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++;
}
}
return 0;
}
Input:
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5{one extra space}
Any way to fix this problem? (Also sorry for the terrible formatting. First question on StackOverflow!)
Looking at your code, this
for
(the first one in thewhile
loop):will always be executed at least ones (because
l<n
, coming from thewhile
's condition).Then you can just do the following:
if
check just for this very firstfor
-loop (use somebool
flag).For example, something like:
This will be rather efficient and short solution - the
if
is in just one loop and the flag will betrue
just once (will avoid cache misses).You can put an
if
condition in yourfor
loopsYou can set a boolean variable
isFirst
totrue
before your printing out any stuff, and test it before eachprintf
statement. IfisFirst
, do not print a space but setisFirst
tofalse
; else print a single space. After that, continue with printing your number without a space.Alternative: Instead of printing your results immediately, create a
results
array. Store your results in there, and when done, print out the results in a tight loop. You can print the first number without a leading space, then loop over the remainder and print them with a leading space.the printf() statement,
results in extra space. use
"%d" without space or use space in the begining as,
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,
You need to suppress the space when you don't need one. You can do it like this:
Add these declarations:
Add this after the first printf:
Change your printf:s to use the new variable:
An answer after accepted answer:
Rather than:
Change the format.