Search code examples
c

"Trouble concatenating char values alongside int and float in C"


#include <stdio.h>

int main()
{
    int a = 10, b, c = 14, d; 
    float e = 7.586, f, g = 682.546, h;
    char i = 'b', j, k = 'h';

    b = a + c;
    f = e + g;
    j = i + k; 
    printf("the value of a and c of addition is  :%d\n",b);
    printf("the value of e and g of addition is  :%f\n",f);
    printf("the value of a and c of addition is  :%c",j);
}

i am trying to concatenate the int,float,character value but i got only the concatenate value of int and float value character cannot...is anyone explain how to solve this problem???


Solution

  • When you add characters, you are actually adding ASCII codes in the background. For example, when you add these two characters ! (ASCII value 33) and " (ASCII value 34), the result is 67, which is C if you look at its equivalent in the ASCII table.

    #include <stdio.h>
    
    int main()
    {
        int a = 10, b, c = 14, d; 
        float e = 7.586, f, g = 682.546, h;
        char i = '!', j, k = '"';
    
        b = a + c;
        f = e + g;
        j = i + k; 
        printf("the value of a and c of addition is  :%d\n",b);
        printf("the value of e and g of addition is  :%f\n",f);
        printf("the value of a and c of addition is  :%c\n",j);
    }
    

    OUTPUT:

    the value of a and c of addition is  :24
    the value of e and g of addition is  :690.132019
    the value of a and c of addition is  :C
    

    If I need to explain in more detail what the system actually does when two char types are added: char data type: 8-bit, i.e. 1 byte. A variable of char type actually contains the numerical equivalent (ASCII code) of an ASCII character. For example, the ASCII code of the character 'a' is 97. When you add, you add the ASCII equivalents, which creates unexpected characters.

    ASCII equivalents in the example you gave

    char i = 'b'; // ASCII 98
    char k = 'h'; // ASCII 104
    char j = i + k; // j = 98 + 104 = 202
    

    You can see the ASCII equivalent on this page.

    The value corresponding to 202 may not be supported by the terminal you are outputting from, so you may see it as "�". You can understand these signs as invalid characters.