Tuesday, 21 August 2012

printf tricks - C Programming

Here I am trying to put some variations of printf statement in C language. These are not all, so lets share the other variations that you know. Here I am assuming that we have little knowledge of C language.
Here I am starting with printf function.

1. printf():
printf function is mainly used to display something on screen in formatted manner.

Ex. 1
printf function executes its parameters from right to left. Here is example,
int a = 10, b = 20;
printf("%d      %d", (a+b), b+=5);
It will display [35      25].

Ex. 2
char a = 'a';
printf("%c      %c      %c", a, a++, a++);
It will output [c      b      a].

Ex. 3
Printf function displays some default values initially.
int a = 10, b = 20, c = 30;
printf("%d      %d      %d");
It will display [30      20      10]. Here also it executes parameters from right.

Ex. 4
If you want to print hex equivalent of integer then use following way,
int a = 12;
printf("%x", a);

Ex. 5
int a = 14;
printf("%4x", a); //It will print hex equivalent of integer but in right justified manner.
printf("%04x"); //It will display int in hex format with right justification with leading places filled with 0's.
printf("%*d", a); //It will leave blanks before number equivalent to that number.

Ex. 6
Printing substring.
char c[5] = {'a', 'b', 'c', 'd', '\0'};
printf("%.*s", 2, c);
It will print [ab] as output.

Ex. 7
int a = 0;
printf("%.0d", a); //It will print only non zero numbers. In this case output will be blank.

If you have more variations then you can share here.

4 comments:

  1. Nice blog brij
    It is realy helpful


    Thanks

    ReplyDelete
  2. #include
    int main()
    {
    int num;
    printf("Enter a number: ");
    scanf("%d",&num);
    printf("%*d",num);
    return(0);
    }

    can you get me the output for this .. i used "%*d,num" but it did not push the num to right instead it prints "2293448"

    ReplyDelete
  3. I don't think that example 3 works

    ReplyDelete