See the 'Width field' subsection in printf format string for an example of how width is passed as an argument to printf.
I got the width algorithm from Finding the length of an integer in C.
I tested my code at Code Chef. If you intend to compile this code with gcc, you will need the -lm option to bring in the library for math.h. See How to compile a C program that uses math.h?.
If you need a different table header, you could adjust the constants 11 in printspaces(11-w) & 5 in printspaces(5-w) till data aligns with the header.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int width(int v){
return floor(log10(abs(v))) + 1;
}
int printspaces(int s){
int x;
for (x=0;x<s;x++)
printf(" ");
}
int main(void){
int i,j,w;
int a[3][4] = {{1,200,3,300},{2,3,1,50},{3,1000,4,1200}};
//int a[3][4] = {{10,200,37,3000},{278,3565,1131,50},{390,100,4567,1200}};
char *separator[4] = {"","","","\n"};
printf("Process No.(Size) Block No.(Size)\n");
for(i=0;i<3;i++){
for (j=0;j<4;j++){
w = width(a[i][j]);
if (j%2==0){
printspaces(11-w);
printf("%*d%s",w,a[i][j],separator[j]);
}
else{
printf("(%*d)",w,a[i][j]);
printspaces(5-w);
printf("%s",separator[j]);
}
}
}
return 0;
}
Here are the results (for the two example arrays in the code):
int a[3][4] = {{1,200,3,300},{2,3,1,50},{3,1000,4,1200}};
Process No.(Size) Block No.(Size)
1(200) 3(300)
2(3) 1(50)
3(1000) 4(1200)
int a[3][4] = {{10,200,37,3000},{278,3565,1131,50},{390,100,4567,1200}};
Process No.(Size) Block No.(Size)
10(200) 37(3000)
278(3565) 1131(50)
390(100) 4567(1200)