Shahir Rahman
Shahir Rahman

Reputation: 11

In C how does a character work

In the program I have given below we take j as a character. We take j=1 but the ascii value of 1 is 49. So why the answer is 15? Is j working as an integer?

#include<stdio.h>

int main()
{
    int i=0;
    char j;

    for(j=1 ; j <=5 ; j++)
    {
        printf("-%c\n",j);
        i=i+j;
        printf("%c\n",i);
    }

    printf("%d",i);

    return 0;
}

Upvotes: 1

Views: 76

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311108

In the loop there is calculated the sum of numbers 1, 2, 3, 4, 5 that indeed is equal to 15.

In this expression

i=i+j;

operand j is converted to type int due to the integer promotions and the result of type int is stored in the variable i.

In this statement

printf("%d",i);

this result as an integer value is outputed.

If you want to deal with character values '1', '2' and so on you could write the loop like

for ( j = '1' ; j <= '5' ; j++ )

and if the ASCII coding is used then variable i will contain the sum of the values 49, 50, 51, 52, 53.

Upvotes: 2

John
John

Reputation: 6678

int i=0;

declares i as int

char j;

declares j as char

for(j=1 ; j <=5 ; j++)

initializes j with an integer, to initialize it with the ASCII value for 1, 49 you could use

for(j='1' ; j <= '1' + 5 ; j++)

but I don't understand what your ultimate goal is and how this would work for you?

    printf("%c\n",i);

Is outputting a char; despite i being an int.

printf("%d",i);

Is outputting an int.

The difference now is the first will exceed the ASCII range of 0-127 on the third iteration, so I would suggest you change it the latter form (of %d).

Upvotes: 0

Related Questions