Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how %c prints value in a C program?

Tags:

c

The following program yields 12480 as the output.

#include<stdio.h>

int main()
{
    char c=48;
    int i, mask=01;
    for(i=1; i<=5; i++)
    {
        printf("%c", c|mask);
        mask = mask<<1;
    }
    return 0;
}

Now, my question is, how "%c" prints the integer value 1, 2, 4, 8, 0 after every loop. It should print a character as a value. If i simply use the following program,

#include<stdio.h>

int main()
{
    char c=48;
    int i, mask=01;
    printf("%c",c); 
    return 0;
}

it prints 0 but when i change the identifier %c to %d it prints 48 . Can anyone please tell me how is this going!?

like image 778
Chandeep Avatar asked Feb 05 '12 11:02

Chandeep


1 Answers

If you use %c, c prints the corresponding ASCII key for the integer value.

Binary of 48 is 110000. Binary of 1 is 000001.

You or them, 110000 | 000001 gives 110001 which is equivalent to 49 in decimal base 10.

According to the ASCII table, corresponding ascii values for 49, 50, 51, etc are '1', '2', '3', etc.

like image 130
Abhijeet Rastogi Avatar answered Sep 23 '22 05:09

Abhijeet Rastogi