pasignature
pasignature

Reputation: 585

Why are the outputs of this C code different when formatting with %c and %d

Take a look at the following piece of code:

#include <stdio.h> 

int main() 
{ 
  int i;

  for (i = 48; i < 58; i++)
  {
    printf("%d", i);
  }
return 0; 
}

The output is: 48495051525354555657 But if you change printf("%d", i); to printf("%c", i); the output becomes: 0123456789

Shouldn't both output 48495051525354555657 Why are the outputs different when substituting d with c?

Upvotes: 2

Views: 408

Answers (4)

Eraklon
Eraklon

Reputation: 4288

Because with %c the i is interpreted as a character and if you look at the ASCII table you can see that 48 represents the character '0', 49 is '1', etc.

Upvotes: 8

mohan
mohan

Reputation: 31

%d is format specifier for signed integers whereas %c is format specifier for charecters . let i=48 when %d is used it prints the integer (prints 48). but when %c is used the 48 is taken as ASCII value and 0 is printed for 48 ascii values 0 = 48 1 = 49 . . . soon hope you understand press the upvote. :) ;)

Upvotes: 2

Akhil Pathania
Akhil Pathania

Reputation: 752

In C when you want to print something you need to provide format specifier. Then the compiler will print the things accordingly.

According to your question %d specifier is for printing number and %c is for printing character.

So when you tried printing integer value using %c format specifier then the system is converting 48-57 in char type and that is '0'-'9'. And if you go further it will print

: ; < = > ? @ A B C and so on.

And this is because system follows ASCII.

Upvotes: 2

Marce
Marce

Reputation: 477

%d prints out a number and %c a character. The ASCII codes for 0-9 are 48-57, so it prints those numbers as characters.

Upvotes: 6

Related Questions