-2

it is printing the value to be 55 instead of 7.

#include <stdio.h>

int main()
{
    char a = '7';
    printf("%d", (int)a);
    return 0;
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Tauqeer
  • 15
  • 3
  • 6
    The value of '7' is 55, the value of 7 is 7, consult your ASCII table. – Dmytro Aug 19 '22 at 23:29
  • 4
    I can **completely** understand having this same question when I was learning C. – Steve Friedl Aug 19 '22 at 23:41
  • 2
    "Why in My Code, Type Casting is not Working in C?" - Type casting is working perfectly fine. It is giving the result the standard is requiring. It is just not the result you *expect*. – Jesper Juhl Aug 20 '22 at 00:33
  • 2
    Hint; messages like "ps. don't downvote me" will *usually* have the direct opposite effect of what you want. – Jesper Juhl Aug 20 '22 at 00:52
  • Does this answer your question? [Printing a char with printf](https://stackoverflow.com/questions/4736732/printing-a-char-with-printf) – phuclv Aug 20 '22 at 01:02
  • 1
    @JesperJuhl - wasn't that said by Barbra Streisand? :-) – Steve Friedl Aug 20 '22 at 02:08

2 Answers2

4

ASCII characters are represented by numbers. The numeric value of the character '7' is 55. As the characters '0' to '9' are laid out sequentially in ASCII, you can subtract '0' from '7' to get the number 7.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 3
    I started with _"Once upon a time, before [ASCII](https://en.wikipedia.org/wiki/ASCII) ..."_ - but, nah. +1 – Ted Lyngmo Aug 19 '22 at 23:39
  • 1
    And thus was a magnificent bit of writing lost to the world. (Not being even slightly sarcastic, by the way.) – Chris Aug 19 '22 at 23:40
0
#include <stdio.h>

int main()
{
char a = '7';
printf("%c",a);
return 0;
}

for character, you need to use %c. Your are getting 55 because in your code you tried to print numerical value of 7.

koushik
  • 1
  • 3