Chapter 5: Managing Input and Output Operations
- LO 5.1: Describe how a character is read
- LO 5.2: Express how a character is written
- LO 5.3: Explain formatted input
- LO 5.4: Discuss formatted output
All programs using I/O functions must include #include <stdio.h> at the beginning. This header file contains declarations for standard input/output functions.
5.1 Reading a Character: getchar()
The getchar() function reads a single character from the keyboard. It returns the character read as an integer value.
char ch; ch = getchar(); // Waits for user to press a key
📝 Worked-Out Problem 5.1
Interactive program using getchar():
#include <stdio.h>
#include <ctype.h>
int main() {
char answer;
printf("Do you like C? (Y/N): ");
answer = getchar();
if (answer == 'Y' || answer == 'y')
printf("Great! You'll love this course.\n");
else
printf("You'll learn to love it!\n");
return 0;
}
Do you like C? (Y/N): Y
Great! You'll love this course.
Character Test Functions (ctype.h)
| Function | Tests |
|---|---|
| isalpha(c) | Is c an alphabetic character? |
| isdigit(c) | Is c a digit? |
| islower(c) | Is c a lowercase letter? |
| isupper(c) | Is c an uppercase letter? |
| isspace(c) | Is c a whitespace character? |
| isalnum(c) | Is c alphanumeric? |
| ispunct(c) | Is c a punctuation mark? |
5.2 Writing a Character: putchar()
The putchar() function writes a single character to the screen.
char ch = 'A';
putchar(ch); // Prints A
putchar('\n'); // Newline
📝 Worked-Out Problem 5.2
Converting case using character functions:
#include <stdio.h>
#include <ctype.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
if (islower(ch))
putchar(toupper(ch));
else if (isupper(ch))
putchar(tolower(ch));
else
putchar(ch);
putchar('\n');
return 0;
}
Output (if input is 'Z'): z
5.3 Formatted Input: scanf()
The scanf() function reads formatted input from the keyboard.
scanf("control string", &variable1, &variable2, ...);
Common scanf Format Codes
| Code | Meaning |
|---|---|
| %d | Read an integer |
| %f | Read a float |
| %lf | Read a double |
| %c | Read a single character |
| %s | Read a string (no spaces) |
| %[^\n] | Read a line including spaces |
| %*d | Skip an integer input |
| %2d | Read integer with field width 2 |
& operator before variable names in scanf() (except for strings). Forgetting the & is a common error that leads to program crashes.
📝 Worked-Out Problem 5.3
Reading integers with field width:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d %*d %d", &a, &b, &c);
printf("a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}
If input is: 10 20 30
The %*d skips the second value (20).
Reading Strings with Spaces
%s stops at whitespace. To read a line with spaces, use:
char line[80];
scanf("%[^\n]", line); // Reads until newline
Reading Mixed Data Types
int count;
char code;
float ratio;
char name[20];
scanf("%d %c %f %s", &count, &code, &ratio, name);
// Input: 15 p 1.575 coffee
5.4 Formatted Output: printf()
The printf() function prints formatted output to the screen.
printf("control string", variable1, variable2, ...);
printf Format Specifiers
| Specifier | Meaning | Example |
|---|---|---|
| %d | Integer | printf("%d", 123); |
| %f | Float | printf("%f", 123.456); |
| %c | Character | printf("%c", 'A'); |
| %s | String | printf("%s", "Hello"); |
| %e | Scientific notation | printf("%e", 123.456); |
| %g | Uses %f or %e (shorter) | printf("%g", 123.456); |
| %x | Hexadecimal | printf("%x", 255); // ff |
| %o | Octal | printf("%o", 8); // 10 |
| %p | Pointer address | printf("%p", &x); |
Field Width and Precision
Format: %[flags][width][.precision]specifier
Examples with number 9876:
%6d→ " 9876" (right-justified, width 6)%-6d→ "9876 " (left-justified)%06d→ "009876" (zero-padded)
Examples with float y = 98.7654:
%7.2f→ " 98.77" (rounded to 2 decimal places)%7.2e→ "9.88e+01" (scientific notation)%-7.2f→ "98.77 " (left-justified)
📝 Worked-Out Problem 5.4
Printing in different formats:
#include <stdio.h>
int main() {
int x = 123;
float y = 98.7654;
char str[] = "HELLO";
printf("Integer:\n");
printf("%d\n", x);
printf("%6d\n", x);
printf("%-6dEND\n\n", x);
printf("Float:\n");
printf("%f\n", y);
printf("%7.2f\n", y);
printf("%7.2e\n", y);
printf("%-7.2fEND\n\n", y);
printf("String:\n");
printf("%s\n", str);
printf("%10s\n", str);
printf("%-10sEND\n", str);
return 0;
}
Integer:
123
123
123 END
Float:
98.765400
98.77
9.88e+01
98.77 END
String:
HELLO
HELLO
HELLO END
5.5 String I/O: gets() and puts()
gets() reads a line of text including spaces. puts() writes a string followed by a newline.
char line[100]; gets(line); // Reads a line until Enter puts(line); // Prints the line and moves to next line
gets() is unsafe (no bounds checking). In modern C, use fgets() instead. However, for learning purposes, many textbooks still use gets().
📝 Worked-Out Problem 5.5
Program using gets() and puts():
#include <stdio.h>
int main() {
char name[50];
char city[50];
printf("Enter your full name: ");
gets(name);
printf("Enter your city: ");
gets(city);
printf("\n--- Information ---\n");
puts(name);
puts(city);
return 0;
}
Enter your full name: John Doe
Enter your city: New York
--- Information ---
John Doe
New York
5.6 Error Detection in Input
scanf() returns the number of items successfully read. This can be used to detect input errors.
int count = scanf("%d %f %s", &a, &b, name);
printf("Items read: %d\n", count);
Key Points to Remember
- Always include
<stdio.h>for I/O functions. - Use
&before variables inscanf()(except for strings). %sinscanf()stops at whitespace.- Use
%[^\n]to read a line with spaces. - In
printf(), width specifies minimum field width. - Precision for floats specifies digits after decimal point.
- Use
-flag for left justification. - Use
0flag for zero padding.
Chapter Exercises
Review Questions
- State true or false:
a) The purpose ofstdio.his to store programs created by users.
b)getchar()can be used to read a line of text.
c) Variables form a legal element of the format control string ofprintf().
d) The format%5swill print only the first 5 characters of a string. - What is the purpose of
scanf()? - What happens when an input data item contains more characters than the specified field width?
- Distinguish between
getchar()andscanf().
Multiple Choice Questions
- String constants are enclosed within ________ symbols.
a) Single quote
b) Double quote
c) []
d) None - Which of the following is used to separate specifiers in a format string within a
scanf()statement?
a) Single white space
b) Comma
c) Double quotes
d) Semi-colon - Which function can be used to print a single character?
a)scanf()
b)printf()
c)putchar()
d) Both b and c
Debugging Exercises
Find errors, if any, in the following statements:
scanf("%c%f%d", city, &price, &year);
scanf("%s%d", city, amount);
scanf("%f, %d, &amount, &year);
printf("%d, %7.2f, %s, price, count, city);
Programming Exercises
- Given the string "WORDPROCESSING", write a program to read it and display in the following formats:
a) WORD PROCESSING
b) WORD
PROCESSING
c) W.P. - Write a program to read three integers using one
scanf()and output them on one line using:
a) threeprintf()statements
b) oneprintf()with conversion specifiers
c) oneprintf()without conversion specifiers - Write a program to print the value 345.6789 in fixed-point format with:
a) 2 decimal places
b) 5 decimal places
c) 0 decimal places - Write a program to input an investment amount and compute its fixed deposit cumulative return after 10 years at 8.75% interest.
Interview Questions
- How will you print the % character on the output screen?
- What will be the output of:
printf("%d", printf("Hello")); - Is it possible to run a program successfully without including
<stdio.h>? - What will be the output of:
printf("%d");(with missing argument)