Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain the Character operations in C language
Character operations in C language involve handling individual characters, which can be alphabetic (A-Z or a-z), numeric (0-9), whitespace, or special symbols. C provides various functions for character input, output, and manipulation.
Syntax
char variable_name = 'character'; char variable_name;
Character Declaration
Characters in C are declared using the char data type and can be initialized with character constants −
#include <stdio.h>
int main() {
char a = 'A'; /* using character constant */
char b = 65; /* using ASCII value */
char c; /* declaration without initialization */
printf("Character a: %c<br>", a);
printf("Character b: %c<br>", b);
printf("ASCII value of a: %d<br>", a);
return 0;
}
Character a: A Character b: A ASCII value of a: 65
Character Input/Output Functions
C provides several functions for character input and output operations −
Example: Basic Character Input/Output
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered: %c<br>", ch);
printf("Enter another character: ");
ch = getchar();
getchar(); /* consume newline */
printf("Character using getchar(): ");
putchar(ch);
printf("<br>");
return 0;
}
Enter a character: A You entered: A Enter another character: B Character using getchar(): B
Example: Line Counting Program
The following program counts the number of lines in input using getchar() −
#include <stdio.h>
int main() {
int count, num;
printf("Enter multiple lines (Ctrl+D/Ctrl+Z to end):<br>");
num = 0;
while ((count = getchar()) != EOF) {
if (count == '<br>') {
++num;
}
}
printf("Number of lines: %d<br>", num);
return 0;
}
Enter multiple lines (Ctrl+D/Ctrl+Z to end): Hi Hello Welcome ^Z Number of lines: 3
Key Points
- Characters are stored as ASCII values (0-127) in memory
-
scanf("%c", &var)reads whitespace characters including newline -
getchar()reads one character at a time from standard input -
putchar()outputs a single character to standard output
Conclusion
Character operations in C provide fundamental building blocks for text processing. Understanding character input/output functions like getchar(), putchar(), and format specifiers enables efficient character manipulation in C programs.
