optional · CSS study notes
II.10 Standard I/O and Statements
⬆️ P-I.II. Programming Fundamentals · Question Bank · Chapter II (2016–2026)
🧠
Remember: Read → validate → compute → display.
Start here — what you should be able to do
- Select the correct C/C++ input function and matching argument types.
- Read names containing spaces and handle leftover newlines.
- Explain statement categories and recover from failed input.
Reading order: foundation checks → full notes and examples → exam traps → self-test without notes → past-paper answers. All sections below remain part of the topic; code examples are kept in full.
Foundation checks
Input rules worth memorising
scanf("%d", &n)needs anint*;scanf("%lf", &d)needs adouble*.printf("%f", value)receives a double after normal argument promotion.- Use a width limit for C string input, or prefer
fgetsfor a complete line. getswas removed from C11; use a bounded alternative.- C++ numeric extraction: check
if (!(cin >> n))before using n. - Before a later
getline, discard the remaining line when appropriate;cin.clear()clears error flags, whileignore()discards characters. std::fixed << std::setprecision(2)gives two digits after the decimal point; include<iomanip>.
1. Standard I/O Streams
- Standard input (stdin): default source of input data, normally the keyboard
- Standard output (stdout): default destination for normal program output, normally the screen
- Standard error (stderr): separate stream for error messages, so they can be redirected independently of normal output
2. I/O in C
printf()— formatted output, uses format specifiers (%dint,%ffloat,%cchar,%sstring)scanf()— formatted input, requires the address-of operator&for non-string variables (e.g.scanf("%d", &age);)getchar()/putchar()— unformatted single-character input/outputgets()/puts()— unformatted string input/output (gets()is unsafe and was removed from C11; use bounded input such as fgets)
3. I/O in C++
cin >>— extraction operator, reads formatted input from stdincout <<— insertion operator, writes formatted output to stdoutcerr— writes to stderr (unbuffered, for errors)getline(cin, str)— reads a full line including spaces (unlikecin >>, which stops at whitespace)
4. Formatted vs Unformatted I/O
- Formatted I/O: data is converted to/from a specific display format using format specifiers or stream operators (
printf/scanf,cin/cout) - Unformatted I/O: raw character-by-character transfer with no type conversion/formatting (
getchar/putchar,cin.get())
5. Statement Types
| Statement Type | Purpose | Example |
|---|---|---|
| Declaration | Introduces an identifier and its type | int x; |
| Expression/Assignment | Evaluates an expression and optionally stores the result | x = a + b; |
| Control | Alters the normal sequential flow | if(x\>0){...} |
| I/O | Transfers data in/out of the program | cin \>\> x; |
| Compound/Block | Groups multiple statements as one unit | { stmt1; stmt2; } |
| Null | Does nothing (just a semicolon) | ; |
6. 💻 Code Examples: C & C++
Formatted vs unformatted I/O, and why reading a full name needs getline/care with whitespace:
C:
#include <stdio.h>
int main(void) {
int age;
char name[20];
printf("Enter name and age: ");
scanf("%19s %d", name, &age); // & needed for age, NOT for the char array (already an address)
printf("Hello %s, age %d\n", name, age);
int c = getchar(); // unformatted single-character input
putchar(c); // unformatted single-character output
return 0;
}
C++:
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
string fullName;
cout << "Enter age: ";
cin >> age;
cin.ignore(); // discard the leftover newline before getline
cout << "Enter full name: ";
getline(cin, fullName); // reads the WHOLE line, including spaces
cout << "Hello " << fullName << ", age " << age << endl;
cerr << "This message goes to stderr" << endl; // separate, unbuffered stream
return 0;
}
cin >> fullNamealone would stop at the first space (e.g. capture only "John" from "John Smith") —getline(cin, fullName)is the fix, matching the Self-Test question above
7. MCQ Traps
scanf()needs&variablefor primitive types (passing an address), but not for a plainchararray/string, since an array name already decays to an addresscin >>stops reading at the first whitespace; usegetline()to capture a full line with spacesstderroutput is typically unbuffered (shows immediately), whilestdoutmay be buffered — relevant when a program crashes mid-execution- A declaration statement doesn't have to allocate an initial value; an assignment statement gives a value to an already-declared variable
8. Self-Test Questions — with answers
Q1. Differentiate stdin, stdout and stderr.
Answer
- stdin: normal input stream.
- stdout: normal results.
- stderr: diagnostic messages; it can be redirected separately.
- Example: read a number from stdin, print its square to stdout, report invalid input to stderr.
Q2. Why does scanf need &x but not &name for a character array?
Answer
%drequires the address of an int, so pass&x.- An array name usually converts to a pointer to its first element, so
namealready supplies a character address. - Use a width limit to avoid overflowing the array.
Q3. How should a full name such as John Smith be read?
Answer
cin >> namereads one whitespace-delimited token.- Use
std::getline(cin, name)for a whole line. - If numeric extraction preceded it, handle the leftover newline first.
Q4. List six broad statement categories with examples.
Answer
- Declaration:
int x = 0;. - Expression/assignment:
x = x + 1;. - Control:
if (x > 0) { ... }. - I/O operation:
cout << x;—syntactically an expression statement. - Compound block:
{ statement1; statement2; }. - Null statement:
;. - These are useful teaching categories; I/O is not a separate formal C++ statement grammar category.
- Differentiate stdin, stdout, and stderr.
- Why does
scanf("%d", &x)need&butscanf("%s", name)(for a char array) does not? - Why would
cin >> name;fail to capture "John Smith" correctly, and what should be used instead? - List the six broad categories of statements in a typical program, with one example each.
Recall check and coverage
- Explain the three learning outcomes at the top without looking.
- Reproduce one example or trace and test a boundary case.
- Answer each self-test, then compare with the key.
- Attempt each recorded past-paper task on this page.
Recorded written references: No direct written record in this topic's current notes. These concepts support the chapter's programming questions.
Evidence limit: this page preserves the question records found in your Notion notes. Disputed labels and questions not checked against original PDFs remain flagged in the Question Bank; this is not a claim of exhaustive original-paper verification.