baskon1 baskon1 - 19 days ago 6
C Question

C, printf loop and line change

I am new at c programming.

I have a 1-d array (size of array given by user, containing seat numbers)

I want to print the result in the screen but divide the results in MULTIPLE rows. Each row should have only 4 elements of the array, and the last one 5 elements.

Probably I will use a for loop combined with printf but can't think of the way to combine them..

So what I have tried and works but is not so elegant is this code, but I will have to repeat it about 15 times..

for (i=0; i < 4; i++)
{
if (seatnr[i]=1) printf("1");
else printf("0");
}
printf("\n");

for (i=4; i <8; i++)
{
if (seatnr[i]=1) printf("1");
else printf("0");
}
printf("\n");
for (i=8; i <12; i++)
{
if (seatnr[i]=1) printf("1");
else printf("0");
}

Answer
for (j = 0; j < n; j+=4)
{
     for (i=j; i < j+4; i++)
     {
         if (seatnr[i]=1) printf("1");
         else printf("0");
     }
     printf("\n");
}
Comments