Reputation: 15
#include<stdio.h>
void main()
{
int cats,dogs,others,total_pets;
cats=10;
dogs=43;
others=36;
total_pets=cats+dogs;
printf("there are %c total pets are",total_pets);
}
Upvotes: 1
Views: 179
Reputation: 82948
See here for ASCII table : http://web.cs.mun.ca/~michael/c/ascii-table.html
And why it printing 5 :-
Actually its '5' not 5. Your code is printing character 5 not decimal 5. When you use %c to print value of an integer variable, printf convert integer value with character equivalent (as you have seen in ASCII table).
You can try this code (or you should write your own)
void main()
{
int num;
printf("Printing ASCII values Table...\n\n");
num = 1;
while(num<=255)
{
// here you can see how %c and %d works for same variable
printf("\nValue:%d = ASCII Character:%c", num, num);
num++;
}
printf("\n\nEND\n");
}
Happy coding.
Upvotes: 4
Reputation: 3589
%c
is the character specifier so printf("there are %c total pets are",total_pets);
prints the ascii character with the value 53, which is the 5
character.
Upvotes: 2
Reputation: 454970
Use %d
in place of %c
in the printf
.
The value of total_pet
is 53
. When you use %c
in printf
you are trying to print the character whose ASCII value if 53
which happens to be 5
.
Upvotes: 10
Reputation: 2781
Because 53 is the place in the ascii chart where '5' sits.
Use %d in your printf instead.
Upvotes: 2
Reputation: 10482
%c is to print a character. Try changing it to %d for the integer value.
What you are printing is the integer value interpreted as a character.
Upvotes: 1
Reputation: 14568
why are you using %c
. use %d
%c single character
%d and %i both used for integer type
%u used for representing unsigned integer
%o octal integer unsigned
%x,%X used for representing hex unsigned integer
%e, %E, %f, %g, %G floating type
%s strings that is sequence of characters
Upvotes: 2
Reputation: 10830
Why are you formatting it as %c Use %d
printf("there are %d total pets are",total_pets);
Upvotes: 3