Chapter 5 Beginner 52 Questions

Practice Questions — Input, Output, and Formatting

← Back to Notes
10 Easy
13 Medium
7 Hard

Topic-Specific Questions

Question 1
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << "Hello" << " " << "World" << endl;
    return 0;
}
Multiple << operators chain outputs sequentially.
Hello World
Question 2
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << "Line 1" << '\n' << "Line 2" << '\n';
    return 0;
}
'\n' inserts a newline character.
Line 1
Line 2
Question 3
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    int a = 3, b = 7;
    cout << a << "+" << b << "=" << a + b << endl;
    return 0;
}
The expression a + b is evaluated before printing.
3+7=10
Question 4
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double pi = 3.14159265;
    cout << fixed << setprecision(2) << pi << endl;
    cout << setprecision(5) << pi << endl;
    return 0;
}
fixed makes setprecision control decimal places. setprecision is persistent.
3.14
3.14159
Question 5
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << setw(8) << 42 << 99 << endl;
    return 0;
}
setw only affects the very next output.
4299
Question 6
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << setfill('*') << setw(10) << 42 << endl;
    return 0;
}
setfill changes the padding character from space to '*'.
********42
Question 7
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << left << setw(10) << "Name" << right << setw(5) << "Age" << endl;
    cout << left << setw(10) << "Sneha" << right << setw(5) << 20 << endl;
    return 0;
}
left/right control alignment within the setw field.
Name Age
Sneha 20
Question 8
Easy
What is the difference between endl and '\n'?
Both produce a newline, but one does extra work.
endl inserts a newline AND flushes the output buffer. '\n' only inserts a newline without flushing. In competitive programming, '\n' is preferred because flushing after every line is slow.
Question 9
Medium
Why does getline read an empty string after cin >>? How do you fix it?
cin >> leaves a character in the buffer.
cin >> reads a value but leaves the newline character ('\n') in the input buffer. When getline is called next, it immediately finds that '\n' and returns an empty string. Fix: use cin.ignore() between cin >> and getline to discard the leftover newline.
Question 10
Medium
What do ios_base::sync_with_stdio(false) and cin.tie(NULL) do?
They disable two synchronization mechanisms for faster I/O.
ios_base::sync_with_stdio(false) disconnects C++ streams from C streams, removing synchronization overhead. cin.tie(NULL) unties cin from cout so cout is not flushed before every cin read. Together they make cin/cout as fast as scanf/printf. After using them, do NOT mix printf/scanf with cout/cin.
Question 11
Hard
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double x = 3.14159;
    cout << setprecision(3) << x << endl;
    cout << fixed << setprecision(3) << x << endl;
    cout << scientific << setprecision(3) << x << endl;
    return 0;
}
Without fixed/scientific, setprecision controls total significant digits.
3.14
3.142
3.142e+00
Question 12
Hard
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << boolalpha;
    cout << (5 > 3) << endl;
    cout << (5 < 3) << endl;
    cout << noboolalpha;
    cout << (5 > 3) << endl;
    return 0;
}
boolalpha prints true/false as words.
true
false
1
Question 13
Hard
What is the difference between cerr and cout? When would you use cerr?
Think about buffering and what happens during a crash.
cout writes to stdout and is buffered -- output may sit in a buffer before being displayed. cerr writes to stderr and is unbuffered -- output appears immediately. Use cerr for error messages (they appear even if the program crashes) and for debug output in competitive programming (judges only check stdout).
Question 14
Easy
What is the output?
#include <cstdio>
int main() {
    printf("%d + %d = %d\n", 3, 4, 3 + 4);
    return 0;
}
%d is the format specifier for integers in printf.
3 + 4 = 7
Question 15
Medium
What is the output?
#include <cstdio>
int main() {
    printf("%.3f\n", 3.14159);
    printf("%10d\n", 42);
    printf("%-10d|\n", 42);
    return 0;
}
%.3f means 3 decimal places. %10d means right-aligned in 10 chars. %-10d means left-aligned.
3.142
42
42 |
Question 16
Hard
What does cin.clear() do and when is it needed?
What happens when cin >> expects an int but receives a letter?
cin.clear() resets the error flags on the cin stream. When cin >> fails (e.g., user enters 'abc' when an int is expected), cin enters a fail state. All subsequent cin reads silently fail. cin.clear() resets this state. You also need cin.ignore() to clear the bad input from the buffer.
Question 17
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    int x = 42;
    cout << "x" << endl;
    cout << x << endl;
    return 0;
}
"x" is a string literal. x (without quotes) is the variable.
x
42
Question 18
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << setfill('0');
    for (int i = 1; i <= 3; i++) {
        cout << setw(4) << i << endl;
    }
    return 0;
}
setfill('0') persists. setw(4) must be repeated for each output.
0001
0002
0003

Mixed & Application Questions

Question 1
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << "A" << endl;
    cerr << "B" << endl;
    cout << "C" << endl;
    return 0;
}
cerr writes to stderr, cout writes to stdout. Both appear on screen.
A
B
C
Question 2
Easy
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << "Hello\tWorld\n";
    cout << "Line\\2" << endl;
    return 0;
}
\t is tab, \n is newline, \\ is a literal backslash.
Hello World
Line\2
Question 3
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double x = 0.1 + 0.2;
    cout << x << endl;
    cout << fixed << setprecision(17) << x << endl;
    return 0;
}
0.1 and 0.2 cannot be represented exactly in binary floating point.
0.3
0.30000000000000004
Question 4
Easy
Write a program that reads a student's name (full name with spaces), roll number (integer), and CGPA (decimal). Print them in a formatted way.
Use cin >> for roll number, cin.ignore() + getline for name.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
    int roll;
    string name;
    double cgpa;
    cout << "Enter roll number: ";
    cin >> roll;
    cin.ignore();
    cout << "Enter full name: ";
    getline(cin, name);
    cout << "Enter CGPA: ";
    cin >> cgpa;
    cout << "Roll: " << roll << endl;
    cout << "Name: " << name << endl;
    cout << "CGPA: " << fixed << setprecision(2) << cgpa << endl;
    return 0;
}
Input: 101, Amit Kumar, 8.75 Output: Roll: 101 Name: Amit Kumar CGPA: 8.75
Question 5
Medium
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << setw(5) << left << 1 << setw(5) << left << 2 << setw(5) << left << 3 << endl;
    return 0;
}
Each number is left-aligned in a 5-character field.
1 2 3
Question 6
Hard
What is the output?
#include <iostream>
using namespace std;
int main() {
    int x = 5;
    cout << "Value: " << x << ", Double: " << x * 2;
    cout << '\n';
    cout << "Address size: " << sizeof(&x) << endl;
    return 0;
}
&x is a pointer. sizeof a pointer depends on the system (32-bit vs 64-bit).
Value: 5, Double: 10
Address size: 8
Question 7
Medium
Write a program that reads n floating-point numbers and prints each with exactly 4 decimal places, right-aligned in a field of width 12.
Use fixed, setprecision(4), and setw(12) for each number.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    int n;
    cin >> n;
    cout << fixed << setprecision(4);
    for (int i = 0; i < n; i++) {
        double x;
        cin >> x;
        cout << setw(12) << x << '\n';
    }
    return 0;
}
Input: 3 3.14 100.5 0.001 Output: 3.1400 100.5000 0.0010
Question 8
Hard
Why should you not use endl in competitive programming? What should you use instead?
Think about what endl does beyond adding a newline.
endl inserts a newline AND flushes the output buffer. Flushing forces the OS to write buffered data to the screen immediately. When printing millions of lines, this flush operation after each line causes a massive slowdown (5-10x). Use '\n' instead, which only adds a newline. The buffer flushes automatically when the program ends.
Question 9
Easy
What is the output?
#include <cstdio>
int main() {
    printf("%05d\n", 42);
    printf("%8.2f\n", 3.14159);
    return 0;
}
%05d means zero-padded to 5 digits. %8.2f means 8 chars wide with 2 decimal places.
00042
3.14
Question 10
Hard
What is the output?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    double d = 123456789.123456789;
    cout << d << endl;
    cout << fixed << setprecision(9) << d << endl;
    return 0;
}
double has ~15 significant digits. The number has 18 digits total.
1.23457e+08
123456789.123456791
Question 11
Medium
Write a program that keeps reading integers until the user enters a non-integer (like a letter). Use cin.fail() to detect bad input and cin.clear() + cin.ignore() to recover. Print the sum of valid integers.
After cin >> fails, cin.fail() returns true.
#include <iostream>
#include <limits>
using namespace std;
int main() {
    int sum = 0, x;
    cout << "Enter integers (non-integer to stop): ";
    while (cin >> x) {
        sum += x;
    }
    cout << "Sum: " << sum << endl;
    return 0;
}
Input: 10 20 30 abc Output: Sum: 60
Question 12
Medium
What is the output?
#include <iostream>
using namespace std;
int main() {
    cout << "Tab:\tEnd" << endl;
    cout << "Quote: \"hello\"" << endl;
    cout << "Backslash: \\" << endl;
    cout << "Null char: " << '\0' << "end" << endl;
    return 0;
}
Escape sequences: \t, \", \\, \0.
Tab: End
Quote: "hello"
Backslash: \
Null char: end

Multiple Choice Questions

MCQ 1
Which header file is needed for setw and setprecision?
  • A. <iostream>
  • B. <iomanip>
  • C. <cstdio>
  • D. <string>
Answer: B
B is correct. <iomanip> (input/output manipulation) provides setw, setprecision, setfill, fixed, left, right, and other formatting manipulators.
MCQ 2
What does cin.ignore() do?
  • A. Ignores the next cin statement
  • B. Discards one character from the input buffer
  • C. Clears the error state of cin
  • D. Resets cin to its default state
Answer: B
B is correct. cin.ignore() discards one character from the input buffer. It is commonly used to remove the leftover newline after cin >> before calling getline.
MCQ 3
What does endl do that '\n' does not?
  • A. Inserts two newlines
  • B. Flushes the output buffer
  • C. Resets formatting
  • D. Clears the screen
Answer: B
B is correct. endl inserts a newline AND flushes the output buffer. '\n' only inserts a newline. Flushing forces buffered output to appear on screen immediately.
MCQ 4
Which stream is unbuffered?
  • A. cout
  • B. cin
  • C. cerr
  • D. clog
Answer: C
C is correct. cerr is unbuffered -- output appears immediately. cout and clog are buffered. This makes cerr reliable for error messages even if the program crashes.
MCQ 5
What does cin >> x stop reading at?
  • A. End of line only
  • B. First whitespace character (space, tab, or newline)
  • C. End of file only
  • D. After exactly one character
Answer: B
B is correct. cin >> skips leading whitespace and reads until the next whitespace character. This is why it cannot read full names with spaces -- it stops at the first space.
MCQ 6
Which manipulator is NOT persistent (resets after one use)?
  • A. fixed
  • B. setprecision
  • C. setw
  • D. setfill
Answer: C
C is correct. setw only affects the very next output and then resets. All other listed manipulators (fixed, setprecision, setfill) are persistent -- they stay in effect until changed.
MCQ 7
What does ios_base::sync_with_stdio(false) do?
  • A. Makes I/O asynchronous
  • B. Disconnects C++ streams from C streams for faster I/O
  • C. Disables all buffering
  • D. Enables multi-threaded I/O
Answer: B
B is correct. It disconnects C++ streams (cin/cout) from C streams (stdin/stdout), removing synchronization overhead. This makes C++ I/O significantly faster but prevents mixing C and C++ I/O.
MCQ 8
What is the printf format specifier for printing a double with 2 decimal places?
  • A. %d
  • B. %2f
  • C. %.2f
  • D. %f2
Answer: C
C is correct. %.2f prints a floating-point number with exactly 2 decimal places. %d is for integers. %2f means minimum width 2 (not 2 decimal places).
MCQ 9
After cin >> n followed by getline(cin, s), what does s contain?
  • A. The next line of input
  • B. An empty string
  • C. The same value as n
  • D. Compilation error
Answer: B
B is correct. cin >> n leaves the newline in the buffer. getline reads that newline immediately and stores an empty string. Fix with cin.ignore() between them.
MCQ 10
What does cin.tie(NULL) do?
  • A. Ties cin to a file
  • B. Prevents cout from being flushed before cin reads
  • C. Disables cin completely
  • D. Makes cin read from stderr
Answer: B
B is correct. By default, cout is flushed before every cin operation (so prompts appear before input). cin.tie(NULL) removes this tie, preventing automatic flushing. This speeds up I/O in competitive programming.
MCQ 11
What does cout << fixed << setprecision(0) << 3.7; print?
  • A. 3
  • B. 4
  • C. 3.7
  • D. 3.
Answer: B
B is correct. fixed with setprecision(0) means zero decimal places. The value 3.7 is rounded to the nearest integer: 4. Note this is rounding, not truncation.
MCQ 12
Which of the following is TRUE about mixing C and C++ I/O after sync_with_stdio(false)?
  • A. It is perfectly safe
  • B. It causes compilation error
  • C. Output may be interleaved or out of order
  • D. It only affects input, not output
Answer: C
C is correct. After disabling synchronization, C streams (printf/stdout) and C++ streams (cout) maintain separate buffers. Output may appear in unexpected order. It compiles fine but produces undefined output ordering.
MCQ 13
What does getline(cin, s) do that cin >> s does not?
  • A. Reads until end of file
  • B. Reads the entire line including spaces
  • C. Reads exactly one character
  • D. Reads binary data
Answer: B
B is correct. cin >> s stops reading at the first whitespace. getline(cin, s) reads until the newline character, capturing spaces and tabs.
MCQ 14
What does setprecision(3) do WITHOUT fixed?
  • A. Shows 3 decimal places
  • B. Shows 3 total significant digits
  • C. Rounds to nearest 3
  • D. No effect
Answer: B
B is correct. Without fixed, setprecision(n) controls the total number of significant digits. For example, setprecision(3) displays 3.14159 as 3.14 (3 significant digits).
MCQ 15
What is the printf format specifier for long long?
  • A. %d
  • B. %ld
  • C. %lld
  • D. %f
Answer: C
C is correct. %lld is the format specifier for long long in printf/scanf. %d is for int, %ld is for long. Using the wrong specifier causes undefined behavior.
MCQ 16
Which escape sequence produces a tab character?
  • A. \n
  • B. \t
  • C. \s
  • D. \b
Answer: B
B is correct. \t is the tab character. \n is newline. \b is backspace. \s is not a valid escape sequence in C++.

Coding Challenges

Challenge 1: Formatted Student Report Card

Easy
Read a student's name (full name with spaces), roll number, and marks in 5 subjects. Print a formatted report card with the name, roll number, each subject mark (2 decimal places), total, and percentage. Use setw for alignment.
Sample Input
101 Meera Krishnan 85.5 90.0 78.5 92.0 88.5
Sample Output
Roll Number: 101 Student Name: Meera Krishnan -------------------------- Subject 1: 85.50 Subject 2: 90.00 Subject 3: 78.50 Subject 4: 92.00 Subject 5: 88.50 -------------------------- Total: 434.50 Percentage: 86.90%
Use cin.ignore() between cin >> and getline. Use fixed, setprecision(2), and setw for formatting.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
    int roll;
    string name;
    double marks[5], total = 0;
    cin >> roll;
    cin.ignore();
    getline(cin, name);
    for (int i = 0; i < 5; i++) {
        cin >> marks[i];
        total += marks[i];
    }
    cout << "Roll Number: " << roll << endl;
    cout << "Student Name: " << name << endl;
    cout << "--------------------------" << endl;
    cout << fixed << setprecision(2);
    for (int i = 0; i < 5; i++) {
        cout << "Subject " << i + 1 << ":" << setw(13) << marks[i] << endl;
    }
    cout << "--------------------------" << endl;
    cout << "Total:" << setw(16) << total << endl;
    cout << "Percentage:" << setw(11) << (total / 5.0) << "%" << endl;
    return 0;
}

Challenge 2: Multiplication Table Formatter

Easy
Read an integer n and print its multiplication table from 1 to 10. Each line should be formatted as: n x i = result, with the result right-aligned in a field of width 4.
Sample Input
7
Sample Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 ... 7 x 10 = 70
Use setw for alignment of both the multiplier and the result.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= 10; i++) {
        cout << n << " x " << setw(2) << i << " = " << setw(4) << n * i << endl;
    }
    return 0;
}

Challenge 3: Interactive Calculator with Error Recovery

Medium
Write a calculator that reads two numbers and an operator (+, -, *, /). Handle division by zero and invalid input. If cin fails (user enters a non-number), use cin.clear() and cin.ignore() to recover and prompt again.
Sample Input
10 / 3
Sample Output
10 / 3 = 3.33
Use cin.fail(), cin.clear(), cin.ignore(). Print result with 2 decimal places. Handle division by zero.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
    double a, b;
    char op;
    cout << "Enter: number operator number" << endl;
    while (!(cin >> a >> op >> b)) {
        cout << "Invalid input. Try again: " << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    cout << fixed << setprecision(2);
    if (op == '+') cout << a << " + " << b << " = " << a + b << endl;
    else if (op == '-') cout << a << " - " << b << " = " << a - b << endl;
    else if (op == '*') cout << a << " * " << b << " = " << a * b << endl;
    else if (op == '/') {
        if (b == 0) cout << "Error: Division by zero" << endl;
        else cout << a << " / " << b << " = " << a / b << endl;
    } else cout << "Unknown operator" << endl;
    return 0;
}

Challenge 4: Fast I/O Speed Test

Medium
Write a program that reads t test cases. For each test case, read n and then n integers. Print the sum of each test case on a new line. Use fast I/O (sync_with_stdio, cin.tie) and '\n' instead of endl.
Sample Input
2 3 1 2 3 4 10 20 30 40
Sample Output
6 100
Must use ios_base::sync_with_stdio(false) and cin.tie(NULL). Must use '\n' instead of endl.
#include <iostream>
using namespace std;
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        long long sum = 0;
        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            sum += x;
        }
        cout << sum << '\n';
    }
    return 0;
}

Challenge 5: Receipt Printer

Hard
Write a program that reads the number of items n, then for each item reads the name (may contain spaces) and price. Print a formatted receipt with item names left-aligned in 20 chars, prices right-aligned in 10 chars (2 decimal places), a separator line, and the total.
Sample Input
3 Masala Dosa 120.00 Filter Coffee 40.50 Gulab Jamun 60.00
Sample Output
-------- RECEIPT -------- Masala Dosa 120.00 Filter Coffee 40.50 Gulab Jamun 60.00 ------------------------------ Total 220.50
Use getline for names, cin >> for prices, cin.ignore() between them. Use iomanip for formatting.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main() {
    int n;
    cin >> n;
    cin.ignore();
    string names[100];
    double prices[100];
    double total = 0;
    for (int i = 0; i < n; i++) {
        getline(cin, names[i]);
        cin >> prices[i];
        cin.ignore();
        total += prices[i];
    }
    cout << "-------- RECEIPT --------" << endl;
    cout << fixed << setprecision(2);
    for (int i = 0; i < n; i++) {
        cout << left << setw(20) << names[i] << right << setw(10) << prices[i] << endl;
    }
    cout << "------------------------------" << endl;
    cout << left << setw(20) << "Total" << right << setw(10) << total << endl;
    return 0;
}

Challenge 6: Number Base Converter

Hard
Write a program that reads an integer and prints it in decimal, octal, hexadecimal (lowercase and uppercase) using cout manipulators (dec, oct, hex, uppercase). Also print using printf format specifiers.
Sample Input
255
Sample Output
Decimal: 255 Octal: 377 Hex (lower): ff Hex (upper): FF
Use cout with dec, oct, hex, uppercase manipulators. Also demonstrate printf with %d, %o, %x, %X.
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
int main() {
    int n;
    cin >> n;
    cout << "Decimal:     " << dec << n << endl;
    cout << "Octal:       " << oct << n << endl;
    cout << "Hex (lower): " << hex << n << endl;
    cout << "Hex (upper): " << hex << uppercase << n << endl;
    cout << nouppercase << dec;
    printf("\nUsing printf:\n");
    printf("Decimal:     %d\n", n);
    printf("Octal:       %o\n", n);
    printf("Hex (lower): %x\n", n);
    printf("Hex (upper): %X\n", n);
    return 0;
}

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn C++ with a live mentor?

Explore our C++ Masterclass