0

I am executing this program Output is 104 in ASCII Code values. It is giving value in ASCII value but how can i get output in number

void main()

{
    char ch1 , ch2, sum;

    ch1 = '2';
    ch2 = '6';
    sum = ch1+ch2;
    printf("sum = %d ", sum);
    getch();
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Can you describe the output you are expecting? Are you looking for it to print 8? – jmq Aug 30 '19 at 12:30
  • You ask "how can i get output in number" - but `104` is a number. Is it not the number you were expecting? What were you expecting? Surely not `8`? `'2'` is an ASCII character with the decimal value 50, while `'6'` is an ASCII character with decimal value 54. 50 + 54 == 104. If you're intending to add `2` and `6` then you should have `ch1 = 2; ch2 = 6;` so that you assign the decimal number values to your variables instead of the ASCII character codes. – brhans Aug 30 '19 at 22:38

2 Answers2

3

Just use the expression

sum = ch1 - '0' + ch2;

and then

printf("sum = %c ", sum);

Here is a demonstrative program

#include <stdio.h>

int main(void) 
{
    char ch1 , ch2, sum;

    ch1 = '2';
    ch2 = '6';
    sum = ch1 -'0' + ch2;

    printf( "sum = %c\n ", sum );
    //            ^^^ 

    return 0;
}

Its output is

sum = 8

Another approach is the following

#include <stdio.h>

int main(void) {
    char ch1 , ch2, sum;

    ch1 = '2';
    ch2 = '6';
    sum = ch1 -'0' + ch2 - '0';

    printf( "sum = %d\n ", sum );
    //            ^^^ 

    return 0;
}

As for your code then in this code snippet

ch1 = '2';
ch2 = '6';
sum = ch1+ch2;

the expression ch1+ch2 is evaluated like 50 + 54 (if there is used the ASCII coding of characters)

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

I think %c is the specifier you are looking for.

hossi
  • 85
  • 6
  • That is how you print a character, but one of the issues is the fact that arithmetic is being done with characters, not the integer values they represent. – Thomas Jager Aug 30 '19 at 12:41
  • Ah you really wanted to print the `8`.. thought I got your question but well.. I didn't. – hossi Aug 30 '19 at 12:48