to print 'x' no of integers per line

Hi Guys!,

I have 156 integers to print. I want to get output in 12*13 matrix

{1,2,2,2,2,3,3,4,4,4,4,4,
1,2,2,2,2,3,3,4,4,4,4,4,
........................
........................
13 rows.................}


How can I modify my printf to do that!

1
2
  for (int j=0; j<156;j++) //check!!
    printf("%d\t", force_enable[j]);



Thanks!!
i guess you can use if(). so if(j%13==0) cout<<endl; try this
Last edited on
closed account (E0p9LyTq)
@thechavinil, one possible change could be:

1
2
3
4
5
6
7
8
9
for (int j = 0; j < 156; j++) //check!!
{
   printf("%d  ", force_enable[j]); // display the current element and some trailing spaces

   if (((j + 1) % 12) == 0) // have 12 columns been displayed?
   {
      printf("%s", "\n");
   }
}


A Windows console screen is 80 characters wide, using a tab code will not produce an output of 12 columns, only 10. I changed the tab to 2 spaces. The output looks messy, but you get your 12 columns.

@MisterWHite, the OP is looking for a matrix of 12 columns. Your code would produce an output of 13 columns, with the first array element printed on a line by itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// http://ideone.com/XNI6JP
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const int limit = 100;

int next()
{
    return rand() % limit;
}

int main()
{
    srand(time(0));

    unsigned columns = 12;
    unsigned line_width = 80;
    unsigned field_width = line_width / columns;

    for (unsigned i = 0; i < 156; ++i)
    {
        printf("%*i", field_width, next());

        if ((i + 1) % columns == 0)
            printf("\n");
    }
}


See: https://wpollock.com/CPlus/PrintfRef.htm#printfWidth

Topic archived. No new replies allowed.