Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
C: Chars


1. C: Chars

2. C: characters
A character is a nonnegative integer code that represents a letter, digit, etc.

A character literal is represented by a character delimited by singe quotes. Here are some character literals.
'H' 'e' 'l' 'l' 'o'


3. Character strings
A character string literal is a sequence of one or more characters delimited by double quotes.
"Hello, World"


4. Differences
In computer memory, the following hold. These are all different representations in memory and cannot be interchanged in program code without appropriate conversions (e.g., type casts, etc.).

5. Character conversion
Here is a C program that assigns the character variable ch1 the literal value '7' and then converts that character value to an integer and outputs both. Here is the C code.

Here is the output of the C code.


6. Character input
Here is a program that inputs a character and echoes that character. The character typed by the user is intended to be 'y' for yes or 'n' for no, but this is not checked so any character could be typed. Here is the C code.

Important: In same cases, a space is needed after the "%c" in the scanf. Otherwise, a null character is input into the character variable. If you do not have the space, your program may work for some inputs but not others.

7. Examples of input and output
Here are some examples of input and output for the above program code.

Here is an example input.

For the above example input, here is the expected output.

Here is an example input.

For the above example input, here is the expected output.

Here is an example input.

For the above example input, here is the expected output.

Note: Checking that user input is valid as called data validation and will be covered later (after code repetition has been covered)

8. Character codes
In the character set codes, everyone agrees that the letter "A" (in English) is the integer code 65, the letter "B" is 66, etc.

The control codes, such as control-A is integer code 1, control-B is integer code 2, etc.

9. Common error
A common (beginning) programming error is to use a char where a string is required or a string where a char is required.
char ch1; // char: use %c and space in scanf/printf char s1[256]; // string: use %s in scanf/printf


10. End of page

11. Multiple choice questions for this page