Introduction to characters in C

Preview

Introduction to characters in C

A character constant is a single characters enclosed in single quotes (‘). A character constant can contain an alphabet, digit, special character or a white space. A character constant can’t contain more than one character in it.

Example

Z , ‘9’ , ‘#’ etc.

Character Variable

A character variable is a variable of char data type.  The character variable can’t hold more than one character. A character variable can be defined as we define other types of variables in C language.

Example

char choice;

In the above example choice is a character variable which can’t hold more than one character in it.

Initialization of a character variable

We can initialize a character variable as we initialize variables of other data types. The syntax to initialize a character variable is

char var_name=’character’;

char is a data type as well as a keyword which specifies that a character variable is being declared.

var_name refers to the name of character variable defined by the programmer. The variable name must follow all the rules of a valid identifier of C Language.

character specifies the single character to be stored in character variable. It must be enclosed within single quotes(‘).

Example

char choice=’N’;

In the above example, char variable choice has been initialized with the value ‘N’.

We can also store any of the escape sequences in a character variable.

Example

char nextline=’\n’;



Program to demonstrate the use of character variable
#include<stdio.h>
int main()
{
char ch;
ch=’A’;
printf(“\nch=%c”,ch);
return(0);
}
Output
ch=A



Reading and Displaying a character variable

We can read and display a character variable just as we read and display a variable of other data type. We can use input functions like scanf(), getche(), getch(), getchar() etc. to read value of a character variable and can use output functions like printf(), putchar(), putch() to display value of a character variable

 

Program to read and display a character variable.
#include<stdio.h>
int main()
{
char ch;
printf(“\nEnter any character”);
scanf(“%c”,&ch);
printf(“\nch=%c”,ch);
return(0);
}
Output
Enter any characterj
ch=j

 



Best Books of C





Lesson tags: declare character variable in c, initialize a character variable in c, read and display character variable, what is a character variable, what is character constant
Back to: C Programming Language