Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am not quite understanding the output of the following function

I wrote a simple sum() function in C with two arguments of integer type. But, while calling the function in main, I passed char type variables. The problem is I am not able to understand the output of the program. Following is the code.:

void sum(int x,int y)
{
    printf(" x=%d  y=%d\n",x,y);
    printf("%d",x+y);
}

void main()
{
    char a,b,add;
    printf("Enter two values: ");
    scanf("%c%c",&a,&b);
    sum(a,b);           //calling
} 

If I input a=A and b=A then it should give me the addition of ASCII values of A, i.e. 130, but it is giving me 97.
When I try to print the value of x and y, it prints x=65 y=32. I don’t understand why it stores 32 in y? Can someone please explain this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is because your input was A A, which is A<spacebar>A. The scanf("%c%c",&a,&b) read exactly two characters, A and <spacebar>, which resulted x = 65(A), y= 32(<spacebar>). If you want to get the intended output, your input should be AA.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading