08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6 ■ Characters

We could print the character value using the specification %c in printf, and we could print

the integer value using %d. For example, the statement

printf("Character: %c, Integer: %d\n", 'T', 'T');

will print

Character: T, Integer: 84

6.3 The Type char

In C, we use the keyword char to declare a variable in which we wish to store a character. For

example, the statement

char ch;

declares ch as a character variable. We could, for instance, assign a character constant to ch,

as follows:

ch = 'R';

ch = '\n';

//assign the letter R to ch

//assign the newline character, code 10, to ch

We could print the character value of a character variable using %c in printf. And we could

print the integer value of a character variable using %d. For instance,

ch = 'T';

printf("Mr. %c\n", ch);

printf("Mr. %d\n", ch);

will print

Mr. T

Mr. 84

6.4 Characters in Arithmetic Expressions

C allows us to use variables and constants of type char directly in arithmetic expressions. When

we do, it uses the integer value of the character. For example, the statement

int n = 'A' + 3;

assigns 68 to n since the code for 'A' is 65.

Similarly, we can assign an integer value to a char variable. For example,

char ch = 68;

143

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!