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
An answer after accepted answer:
Rather than:
while (k < m && l < n) {
...
printf("%d ", a[k][i]);
...
printf("%d ", a[i][n-1]);
...
printf("%d ", a[m-1][i]);
...
printf("%d ", a[i][l]);
...
}
Change the format.
const char *format = "%d";
while (k < m && l < n) {
...
printf(format, a[k][i]);
format = " %d";
...
printf(format, a[i][n-1]);
...
printf(format, a[m-1][i]);
...
printf(format, a[i][l]);
...
}
fputc('\n', stdout); // if desired.
You can set a boolean variable isFirst
to true
before your printing out any stuff, and test it before each printf
statement. If isFirst
, do not print a space but set isFirst
to false
; 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.
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<n
, coming from the while
's condition).
Then you can just do the following:
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).
You can put an if
condition in your for
loops
for (i = l; i < n; ++i)
{
printf("%d", a[k][i]);
if(i < n-1)
printf(" ");
}
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++;
}
You need to suppress the space when you don't need one. You can do it like this:
Add these declarations:
char *format = "%d";
int first_number = 1;
Add this after the first printf:
if (first_number) {
/* Now we want a space between numbers */
first_number = 0;
format = " %d";
}
Change your printf:s to use the new variable:
printf(format, ...);