C Programming · Unit 3 · 2 hrs
Input and Output
Exam-focused notes for Input and Output (C Programming, CSC115): what the TU syllabus asks and how it has actually been tested, with 3 solved past questions from this unit.
Input and Output in short
This chapter covers how a C program reads data from the keyboard and writes it back to the screen, and the format specifiers that control exactly how that data is presented.
What this unit covers
- Conversion specification
- Reading a character
- Writing a character
- I/O operations
- Formatted I/O
Formatted I/O
2081 · 5 marks
Describe different formatted input and output functions. Why do we use them? [4+1]
I/O operations
2077 · 5 marks
What do you mean by unformatted I/O? Explain. [5]
Show solved answerHide answer
Unformatted I/O in C
Definition
Unformatted I/O refers to input/output functions in C that read or write data without any format specification. These functions do not require a format string (like %d, %f, etc.) and deal with raw characters or strings directly. They are simpler and faster than formatted I/O functions like scanf() and printf().
Key Characteristics
- No format specifiers are used.
- They work directly with characters and strings.
- They are declared in the header file
<stdio.h>. - They are mainly used for simple character-level or string-level input and output.
Unformatted I/O Functions in C
1. Character Input/Output Functions
| Function | Purpose |
|---|---|
getchar() | Reads a single character from standard input (keyboard) |
putchar() | Writes a single character to standard output (screen) |
Syntax:
char ch;
ch = getchar(); // reads one character
putchar(ch); // prints one character
Example:
#include <stdio.h>
int main() {
char ch;
ch = getchar(); // user types a character
putchar(ch); // prints that character
return 0;
}
2. String Input/Output Functions
| Function | Purpose |
|---|---|
gets() | Reads a string (including spaces) from standard input |
puts() | Writes a string to standard output followed by a newline |
Syntax:
char name[50];
gets(name); // reads a full line as string
puts(name); // prints the string
Example:
#include <stdio.h>
int main() {
char name[50];
gets(name); // reads string with spaces
puts(name); // prints string and moves to new line
return 0;
}
Difference: Unformatted vs Formatted I/O
| Feature | Unformatted I/O | Formatted I/O |
|---|---|---|
| Format specifier | Not required | Required (%d, %f, etc.) |
| Functions | getchar(), putchar(), gets(), puts() | scanf(), printf() |
| Data type handled | Characters and strings only | Any data type |
| Complexity | Simple | More flexible |
Summary
Unformatted I/O functions are used when the program needs to handle raw characters or strings without worrying about data types or format specifiers. They are straightforward, easy to use, and suitable for simple input/output operations in C programs.
Make Unit 3 stick
Practice CSC115 with flashcards & quizzes