Chapter 5: Managing Input and Output Operations

📌 Learning Objectives
  • 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
📁 Header Files:

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;
}
Output:
Do you like C? (Y/N): Y
Great! You'll love this course.

Character Test Functions (ctype.h)

FunctionTests
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 'a'): A
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

CodeMeaning
%dRead an integer
%fRead a float
%lfRead a double
%cRead a single character
%sRead a string (no spaces)
%[^\n]Read a line including spaces
%*dSkip an integer input
%2dRead integer with field width 2
⚠️ Important: Always use the & 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

a = 10, b = 20, c = 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

SpecifierMeaningExample
%dIntegerprintf("%d", 123);
%fFloatprintf("%f", 123.456);
%cCharacterprintf("%c", 'A');
%sStringprintf("%s", "Hello");
%eScientific notationprintf("%e", 123.456);
%gUses %f or %e (shorter)printf("%g", 123.456);
%xHexadecimalprintf("%x", 255); // ff
%oOctalprintf("%o", 8); // 10
%pPointer addressprintf("%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;
}
Output:
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
⚠️ Security Note: 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;
}
Output:
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 in scanf() (except for strings).
  • %s in scanf() 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 0 flag for zero padding.

Chapter Exercises

Review Questions

  1. State true or false:
    a) The purpose of stdio.h is 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 of printf().
    d) The format %5s will print only the first 5 characters of a string.
  2. What is the purpose of scanf()?
  3. What happens when an input data item contains more characters than the specified field width?
  4. Distinguish between getchar() and scanf().

Multiple Choice Questions

  1. String constants are enclosed within ________ symbols.
    a) Single quote
    b) Double quote
    c) []
    d) None
  2. 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
  3. 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

  1. 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.
  2. Write a program to read three integers using one scanf() and output them on one line using:
    a) three printf() statements
    b) one printf() with conversion specifiers
    c) one printf() without conversion specifiers
  3. 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
  4. Write a program to input an investment amount and compute its fixed deposit cumulative return after 10 years at 8.75% interest.

Interview Questions

  1. How will you print the % character on the output screen?
  2. What will be the output of: printf("%d", printf("Hello"));
  3. Is it possible to run a program successfully without including <stdio.h>?
  4. What will be the output of: printf("%d"); (with missing argument)