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
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 lwhile'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).