1. getchar()
Description:
- Reads a single character from the standard input (keyboard).
- Input is buffered, so you need to press
Enter
after entering the character.
Syntax:
char ch = getchar();
#include <stdio.h>
int main() {
char ch;
printf(“Enter a character: “);
ch = getchar(); // Reads a single character
printf(“You entered: “);
putchar(ch); // Prints the character
return 0;
}
Input:
A
Output:
Enter a character: You entered: A
2. putchar()
Description:
- Writes a single character to the standard output (console).
- Useful for printing characters one at a time.
Syntax:
putchar(ch);
Example:
#include <stdio.h>
int main() {
char ch = ‘H’;
putchar(ch); // Prints the character ‘H’
putchar(‘\n’); // Prints a newline character
return 0;
}
Output:
H
3. scanf()
Description:
- Reads formatted input from the standard input (keyboard).
- Requires a format specifier to indicate the type of input.
Syntax:
scanf("format_specifier", &variable);
Example:
#include <stdio.h>
int main() {
int num;
printf(“Enter a number: “);
scanf(“%d”, &num); // Reads an integer
printf(“You entered: %d\n”, num);
return 0;
}
Input:
25
Output:
Enter a number: You entered: 25
4. printf()
Description:
- Writes formatted output to the standard output (console).
- Requires a format specifier to control the output.
Syntax:
printf("format_specifier", variable);
Example:
#include <stdio.h>
int main() {
int num = 10;
printf(“The value of num is: %d\n”, num); // Prints an integer
return 0;
}
Output:
The value of num is: 10
Combined Example Program:
#include <stdio.h>
int main() {
char ch;
int num;
// getchar() and putchar()
printf(“Enter a character: “);
ch = getchar();
printf(“You entered: “);
putchar(ch);
printf(“\n”);
// scanf() and printf()
printf(“Enter a number: “);
scanf(“%d”, &num);
printf(“You entered: %d\n”, num);
return 0;
}
Input:
A
45
Output:
Enter a character: You entered: A
Enter a number: You entered: 45
Summary Table
Function | Purpose | Example |
---|---|---|
getchar() |
Reads a single character from input. | ch = getchar(); |
putchar() |
Writes a single character to output. | putchar(ch); |
scanf() |
Reads formatted input (e.g., numbers, strings). | scanf("%d", &num); |
printf() |
Writes formatted output (e.g., text, numbers). | printf("Value: %d", num); |