Arjun
Arjun

Reputation: 15

Need Explanation for the code. Can someone please explain why the output of the code is -32?

    main() {     
        char c1='a' , c2='A';     
        int i=c2-c1;     
        printf("%d", i); 
    }

What is the output of this code. Please explain why? I know the Answer is -32 but Can someone explain why it's -32?

Upvotes: -5

Views: 124

Answers (2)

John Doe
John Doe

Reputation: 1869

Every ascii char is stored as a number between 0 and 127 inclusive, looking at the ascii table you can see that a is stored as 97 while A is stored as 65.

What you are doing is subtracting a from A and then printing it as integer.

Hence why the result is 65-97=-32

Upvotes: 5

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

please explain why the output of the code is -32?

It is because the used compiler uses the ASCII encoding character set where codes of upper case letters are less than codes of corresponding lower case letters by 32.

Here is a demonstrative program.

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    for ( char upper_case = 'A'; upper_case <= 'Z'; ++upper_case )
    {
        char lower_case = tolower( ( unsigned char )upper_case );
        
        printf( "%c = %d, %c = %d, %c - %c = %d\n",
                upper_case, upper_case, lower_case, lower_case, 
                upper_case, lower_case,
                upper_case - lower_case );
    }
    
    return 0;
}

Its output is

A = 65, a = 97, A - a = -32
B = 66, b = 98, B - b = -32
C = 67, c = 99, C - c = -32
D = 68, d = 100, D - d = -32
E = 69, e = 101, E - e = -32
F = 70, f = 102, F - f = -32
G = 71, g = 103, G - g = -32
H = 72, h = 104, H - h = -32
I = 73, i = 105, I - i = -32
J = 74, j = 106, J - j = -32
K = 75, k = 107, K - k = -32
L = 76, l = 108, L - l = -32
M = 77, m = 109, M - m = -32
N = 78, n = 110, N - n = -32
O = 79, o = 111, O - o = -32
P = 80, p = 112, P - p = -32
Q = 81, q = 113, Q - q = -32
R = 82, r = 114, R - r = -32
S = 83, s = 115, S - s = -32
T = 84, t = 116, T - t = -32
U = 85, u = 117, U - u = -32
V = 86, v = 118, V - v = -32
W = 87, w = 119, W - w = -32
X = 88, x = 120, X - x = -32
Y = 89, y = 121, Y - y = -32
Z = 90, z = 122, Z - z = -32

If your compiler would use the EBCDIC encoding character set then the difference between codes of upper case letters and corresponding lower case letters is equal to 64.

I know the Answer is -32 but

The answer depends on the used encoding character set. It may be for example equal to -32 or -64.:)

Upvotes: 3

Related Questions