Reputation: 2938
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!?
Upvotes: 7
Views: 33622
Reputation: 17244
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.
Upvotes: 8
Reputation: 500933
It actually prints out the characters '1'
, '2'
, '4'
etc.
The numeric value of c|mask
gets interpreted as an ASCII code. The ASCII code of '0'
is 48.
To make the code a little clearer, you could change
char c=48;
to
char c='0';
The two forms are equivalent.
Upvotes: 3