How can I create a code where the spacing of the of the Numbers and Months is equidistant from one another. The code source code has been gotten in the answer of issue.
#include <stdio.h>
#define MAX_LEN 32
int main() {
int Numbers[12] = {3, 4, 5, 1, 2, 7, 8, 9, 3, 4, 7, 8};
char Months[][MAX_LEN] = {"Jan", "Feb", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
for (int i = 0; i < 12; i++)
printf("%s: %d\n", Months[i], Numbers[i]);
return 0;
}
Output
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
Expected Output:
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
You can use extra modifiers in your format string to make printf() align things correctly:
%10s will print a string to a (maximum) column of width 10, padding to the left with spaces. If your string is longer than 10 characters, it prints the full string though so bear this in mind. So your particular example:char Months[][MAX_LEN] = {"Jan", "Feb", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};
for (int i = 0; i < 12; i++) {
/* Note the 10 here! */
printf("%10s: %d\n", Months[i], Numbers[i]);
}
Results in
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
If you want to left-justify your strings, you simple prepend a - before the integer value, i.e.:
printf("%-10s: %d\n", Months[i], Numbers[i]);
Which produces
Jan : 3
Feb : 4
March : 5
April : 1
May : 2
June : 7
July : 8
August : 9
September : 3
October : 4
November : 7
December : 8
* which allows you to state the length to pad to variably in the printf() call. To use it you calculate the length you wish to pad to as an extra argument:int myPadWidth = 15;
/* calculate the length of Months[i] each loop and cast size_t result to int */
int lenMonths = (int)strlen(Months[i]);
/* Note the extra argument in the printf call here! */
printf("%s: %*d\n",Months[i],myPadWidth-lenMonths,Numbers[i]);
Which would result in
Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With