tags:

views:

156

answers:

5

In this code what is the role of the symbol "%3d"? I know that % means refer to a variable.

This is the code:

#include <stdio.h>
int main(void)
{
    int t, i, num[3][4];
    for(t=0; t<3; ++t)
        for(i=0; i<4; ++i)
            num[t][i] = (t*4)+i+1;
    /* now print them out */
    for(t=0; t<3; ++t) {
        for(i=0; i<4; ++i)
            printf("%3d ", num[t][i]);
        printf("\n");
    }
    return 0;
}
+10  A: 

That is a format specifier to print a decimal number (d) in three (at least) digits (3).

From man printf:

An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given) to fill out the field width.

Potatoswatter
Also here: http://www.cplusplus.com/reference/clibrary/cstdio/printf/
Austin Salonen
opengroup.org is better: http://www.opengroup.org/onlinepubs/9699919799/functions/fprintf.html
Potatoswatter
A: 

It is a formatting specification. %3d says: print the argument as a decimal, of width 3 digits.

aioobe
A: 

Literally, it means to print an integer padded to three digits with spaces. The % introduces a format specifier, the 3 indicates 3 digits, and the d indicates an integer. Thus, the value of num[t][i] is printed to the screen as a value such as " 1", " 2", " 12", etc.

Mac
+5  A: 

%3d can be broken down as follows:

  • % means "Print a variable here"
  • 3 means "use at least 3 spaces to display, padding as needed"
  • d means "The variable will be an integer"

Putting these together, it means "Print an integer, taking minimum 3 spaces"

See http://www.cplusplus.com/reference/clibrary/cstdio/printf/ for more information

Slokun
A: 

Thanks Guys For Your Answer !

Stack Overflow is not a forum. Please do not post answers which are not actually answers, like this one. (There is a delete button under the post which you can use to remove this one.) Instead, you can add a comment to any answer that helped you, and you can accept whichever answer helped you the most by clicking the checkmark next to it.
Michael Myers