3.1 Structure of C++ Programs
Hello there! Welcome to Chapter 3. Now that we have learned about algorithms and data structures, it is time to get our hands dirty with actual C++ programming. I know you might be a little nervous, but trust me — by the end of this chapter, you will feel much more confident. Let us start from the very beginning: what does a C++ program look like?
Every C++ program has a specific structure. Think of it like building a house — you need a foundation, walls, and a roof. In C++, the structure is made up of several parts that work together. Let me walk you through each part one by one.
The Basic Structure of a C++ Program
Here is a simple C++ program. Do not worry if you do not understand every line yet. We will break it down completely.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}Now, let me explain each part of this program step by step. This is very important for your exam, so pay close attention!
1. The #include Directive (Header Files)
The very first line #include <iostream> is called a preprocessor directive. What does that mean? Well, before your C++ code is actually compiled, a program called the preprocessor runs first. It looks for lines that start with # and handles them.
The word include tells the preprocessor: “Go find the file called iostream and bring all its content right here, at the top of my program.” The iostream file stands for Input Output Stream. It contains the definitions we need to use cout (for output) and cin (for input). Without this line, the compiler would not know what cout means!
Exam Tip: #include <iostream> is the most common header file in C++. Other important ones include <cmath> for math functions, <iomanip> for formatting output, and <string> for string operations.
2. The using namespace std; Line
This line tells the compiler that we are using the standard namespace. But wait — what is a namespace? Think of a namespace as a container for names. The C++ standard library puts many things (like cout, cin, endl) inside a namespace called std.
If we did NOT write this line, we would have to write std::cout instead of just cout every single time. That gets very tedious! So this line saves us typing. It is like saying: “Hey compiler, whenever I say cout, I mean std::cout.”
Warning for Exam: In larger projects, using using namespace std; can cause name conflicts. But for your course level, it is perfectly fine and expected. Just know that examiners sometimes ask why we use it — now you can explain!
3. The main() Function
int main() is the heart of every C++ program. Every C++ program MUST have a main() function. This is where the execution begins. When you run your program, the computer looks for main() and starts executing code from the first line inside it.
The word int before main() means this function returns an integer value. The return 0; at the end sends 0 back to the operating system, which means “the program ended successfully.” If you return a non-zero value, it typically signals an error.
Quick question for you: Can a C++ program have two main() functions? Think about it… No! There can only be ONE main() function. The compiler would get confused otherwise.
4. The Curly Braces { }
The opening brace { marks the beginning of the function body, and the closing brace } marks the end. Everything between these braces is part of the main() function. This is a rule in C++ — every function must have its body enclosed in braces.
5. The Statement cout << "Hello, World!" << endl;
This is the actual instruction that prints text on the screen. Let us break it down:
cout— pronounced “see-out” — is the standard output object. It sends data to the screen.<<— this is the insertion operator. Think of it as an arrow pointing left, pushing data towardcout."Hello, World!"— this is a string literal. The text inside double quotes gets printed exactly as written.endl— this stands for end line. It moves the cursor to the next line (like pressing Enter).;— the semicolon marks the END of a statement. Every C++ statement MUST end with a semicolon. Forgetting it is the most common beginner mistake!
Key Exam Note: The semicolon ; is a statement terminator in C++. Preprocessor directives (like #include) and function headers (like int main()) do NOT need semicolons. Only executable statements do.
Practice Questions — Structure of C++ Programs
Q1. Which of the following is TRUE about the main() function in C++?
Answer: C
Execution of every C++ program always begins from the main() function. There can only be ONE main() function — option A is wrong. The main() function typically returns an int, not a float — option B is wrong. The main() function is mandatory — option D is wrong.
Q2. What is the purpose of #include <iostream> in a C++ program?
Answer: B
#include <iostream> is a preprocessor directive that includes the header file for input/output streams. This file contains declarations for cout, cin, and endl. It does NOT define main(), declare variables, or compile the program.
Q3 (Fill in the Blank). The _________ operator is used with cout to send output to the screen in C++.
Answer: Insertion operator (<<)
The insertion operator << pushes data toward the cout object for display on screen. The opposite operator >> (extraction operator) is used with cin for input.
3.2 Compilation Process of C++
Great job so far! Now let me ask you something: You write C++ code in English-like text, but the computer only understands binary (0s and 1s). So how does your code actually become something the computer can run?
This is where the compilation process comes in. It is a multi-step process that transforms your human-readable source code into machine-executable code. Understanding this process is extremely important for exams. Let me walk you through each step carefully.
Step 1: Writing the Source Code
You write your C++ program in a text editor or IDE (like Code::Blocks, Dev-C++, or Visual Studio). The file is saved with a .cpp extension. This is your source code — it is in human-readable form.
Step 2: Preprocessing
The preprocessor is the first program that processes your code. It does NOT understand C++ syntax. Instead, it looks for lines starting with # and performs these tasks:
- Includes header files — replaces
#include <iostream>with the actual content of the iostream file. - Removes comments — all
//and/* */comments are stripped out because the compiler does not need them. - Processes macros — handles
#definedirectives (we will learn about this later).
After preprocessing, you get what is called expanded source code or translation unit.
Step 3: Compilation
Now the compiler takes the expanded source code and translates it into object code (also called machine code). The object code is in binary form, but it is not yet a complete program. It is saved with a .obj (Windows) or .o (Linux) extension.
During this step, the compiler checks your code for syntax errors. If it finds any, it stops and shows error messages. If there are no errors, it produces the object file.
Step 4: Linking
The linker is the final step. It takes your object file and links it with any library files that your program needs. For example, when you use cout, the actual implementation is in a library file. The linker connects your code to that library code.
The output of the linker is the executable file — a .exe file on Windows. This is the file you can actually run!
Exam Note — Key Difference: The compiler checks syntax and converts one .cpp file to .obj. The linker combines multiple .obj files and library files into a single .exe. Many students confuse these two — do not be one of them!
Step 5: Execution
When you run the executable, the operating system loads it into RAM and the CPU begins executing the instructions starting from main().
Important: What About Interpreters?
Remember from Chapter 1 that compilers translate the ENTIRE program before execution, while interpreters translate one line at a time. C++ uses a compiler, not an interpreter. This makes C++ programs faster at runtime, but the compilation step takes time. Languages like Python use interpreters.
Practice Questions — Compilation Process
Q1. In the C++ compilation process, which component is responsible for removing comments and expanding #include directives?
Answer: C
The preprocessor handles all directives starting with #, including #include (file inclusion) and #define (macro definition). It also strips out all comments from the source code before the compiler sees the code. The compiler checks syntax, the linker combines object files, and the loader loads the program into memory.
Q2. What is the output file produced by the linker in C++?
Answer: C
The linker produces the executable file (.exe on Windows). The compiler produces the object file (.obj). The source code file (.cpp) is what you write. The header file (.h) is included during preprocessing. The linker’s specific job is to combine object files with libraries into a runnable executable.
Q3 (True/False). The C++ compiler can detect logical errors in your program.
Answer: False
The compiler can ONLY detect syntax errors (like missing semicolons, wrong keywords, mismatched braces). It cannot detect logical errors. A logical error is when your program runs without crashing but produces the wrong result. For example, writing a + b instead of a - b is a logical error — the compiler sees valid syntax, so it will not catch it. Only careful testing and debugging can find logical errors.
3.3 Error Types in Programming
Alright class, let us talk about something every programmer deals with: errors. No matter how careful you are, you will make mistakes. That is completely normal! The key is understanding what type of error you made so you can fix it quickly. For your exam, you must know the three main types of errors.
1. Syntax Errors
Syntax errors are like grammar mistakes in English. Just like a sentence must follow grammar rules, your C++ code must follow the syntax rules of the language. The compiler catches these errors during the compilation phase.
Common causes of syntax errors:
- Missing semicolon
;at the end of a statement - Mismatched braces
{ }or parentheses( ) - Misspelled keywords (writing
inhludeinstead of#include) - Using undeclared variables
- Missing double quotes around strings
// Example of syntax error:
int main()
{
cout << "Hello" // Missing semicolon here!
return 0;
}
// Compiler error: expected ';' before 'return'Important: A program with syntax errors will not compile at all. You must fix ALL syntax errors before the compiler can produce an object file. The compiler tells you the line number where it detected the error — use that to find and fix it.
2. Logical Errors (Semantic Errors)
Logical errors are the trickiest type. Your program compiles successfully and runs without crashing, but it produces the wrong result. The compiler cannot catch these because the syntax is perfectly valid.
// Example of logical error:
int a = 10, b = 5;
int sum = a - b; // Should be a + b for sum!
cout << "Sum: " << sum; // Prints 5, but correct answer is 15
// No error message! Program runs fine but gives wrong output.Other examples: using > instead of < in a condition, wrong formula in a calculation, off-by-one errors in loops. You must test your program with known inputs and check if the output is correct to find logical errors.
3. Runtime Errors
Runtime errors occur while the program is running. The program compiles fine, but when it executes, something goes wrong and the program crashes or behaves unexpectedly.
// Example of runtime error:
int a = 10, b = 0;
int result = a / b; // Division by zero!
cout << result; // Program crashes hereCommon runtime errors include: division by zero, accessing an invalid array index, running out of memory, stack overflow from infinite recursion. These errors are detected by the operating system or runtime environment, not the compiler.
Practice Questions — Error Types
Q1. A student writes int result = 25 / 0; in a C++ program. The program compiles successfully but crashes during execution. What type of error is this?
Answer: C
Division by zero is a classic runtime error. The syntax is correct (the compiler allows it), but during execution, dividing by zero causes the program to crash. The operating system detects this illegal operation and terminates the program. This is NOT a logical error because the program does not produce a wrong result — it simply cannot complete the operation.
Q2. Which of the following statements about logical errors is TRUE?
Answer: C
Logical errors are the most dangerous because the program compiles and runs without any error messages, but produces incorrect results. The compiler cannot detect them (A is wrong). The program compiles fine (B is wrong). They are actually the HARDEST to find and fix (D is wrong), because there are no error messages to guide you.
Q3 (Fill in the Blank). Errors that are detected by the _________ during the compilation phase are called syntax errors.
Answer: Compiler
The compiler checks your source code against C++ syntax rules. Any violation (missing semicolons, wrong keywords, undeclared variables, mismatched brackets) is flagged as a syntax error. The preprocessor handles # directives, the linker combines files, and the loader loads the program into memory — none of these detect syntax errors.
3.4 Basic Elements of C++ Programming
Now we are getting to the core of C++! These are the building blocks you will use in every single program you write. Pay very close attention to each concept because they are all heavily tested in exams.
3.4.1 Identifiers
Identifiers are the names you give to things in your program — variables, functions, constants, and so on. When you write int age;, the word age is an identifier. Simple, right? But there are rules you must follow when naming things.
Rules for Identifiers (Must Memorize!)
- Must begin with a letter (a-z, A-Z) or underscore (_). It CANNOT start with a digit.
- Can contain letters, digits (0-9), and underscores only. No spaces, no special characters like @, #, $, %.
- Cannot be a reserved keyword. You cannot name a variable
int,return,if, etc. - C++ is case-sensitive.
Age,age, andAGEare THREE different identifiers. - No length limit (practically), but keep names meaningful and reasonable.
// VALID identifiers:
int age;
int _count;
int studentName;
int marks1;
int total_marks;
// INVALID identifiers:
int 1stMark; // Error: starts with a digit
int my age; // Error: contains a space
int student@; // Error: contains special character @
int int; // Error: 'int' is a reserved keyword
int float; // Error: 'float' is a reserved keywordExam Tip: Examiners love to test identifier rules with tricky examples. Remember: _123 is valid (starts with underscore), my_var is valid, my-var is INVALID (hyphen is not allowed), while is INVALID (keyword). Also, MyVar and myvar are DIFFERENT because C++ is case-sensitive.
Practice Questions — Identifiers
Q1. Which of the following is a VALID C++ identifier?
Answer: C
_totalMarks is valid because it starts with an underscore, and the rest are letters. 2ndValue starts with a digit — invalid. my-variable contains a hyphen — invalid. class is a reserved keyword — invalid.
Q2. In C++, are score and Score the same identifier?
Answer: B
C++ is strictly case-sensitive. score and Score are two completely different identifiers. This has nothing to do with namespaces or data types. This rule always applies in C++.
3.4.2 Variables
Now, what exactly is a variable? Think of a variable as a container or a box in the computer’s memory. You put a value in it, and you can change (vary) that value later — that is why it is called a “variable”!
Before you use a variable in C++, you must declare it. Declaration tells the compiler: “I need a box of this size (data type) with this name.”
// Declaring variables
int age; // A box named 'age' that holds integers
float salary; // A box named 'salary' that holds decimal numbers
char grade; // A box named 'grade' that holds a single character
// Declaring AND initializing at the same time
int age = 20;
float salary = 3500.50;
char grade = 'A';I want you to notice something important: when we store a character, we use single quotes like 'A'. But when we print a string of text with cout, we use double quotes like "Hello". Do not mix these up in the exam!
3.4.3 Data Types
Data types tell the compiler what kind of data a variable will hold. This is crucial because different types of data need different amounts of memory. C++ has several built-in data types. Let me explain each one clearly.
Fundamental (Primitive) Data Types
| Data Type | Keyword | Size (typical) | Range (approximate) | Example |
|---|---|---|---|---|
| Integer | int | 4 bytes | -2,147,483,648 to 2,147,483,647 | int age = 25; |
| Float | float | 4 bytes | 6-7 significant digits | float price = 19.99f; |
| Double | double | 8 bytes | 15-16 significant digits | double pi = 3.1415926535; |
| Character | char | 1 byte | -128 to 127 (or 0 to 255) | char ch = 'X'; |
| Boolean | bool | 1 byte | true or false | bool passed = true; |
Let me explain the important details about each type:
Integer Type (int)
This is the most commonly used data type. It stores whole numbers — positive, negative, and zero. It does NOT store decimal numbers. If you write int x = 3.7;, the compiler will truncate (cut off) the decimal part and store only 3.
Floating-Point Types (float and double)
These store numbers with decimal points. The word “float” means the decimal point can “float” to any position. float gives about 6-7 digits of precision, while double (double precision) gives about 15-16 digits. When you write a float literal, it is good practice to add f at the end: 19.99f. Without the f, C++ treats it as a double by default.
Character Type (char)
A char stores exactly one character. Internally, it stores the ASCII code of that character as a number. For example, 'A' is stored as 65, '0' is stored as 48. This is why you can do math with characters!
char ch = 'A';
cout << ch; // Prints: A
cout << (int)ch; // Prints: 65 (ASCII value)Boolean Type (bool)
A bool can only hold one of two values: true (which equals 1) or false (which equals 0). This is used for conditions and flags.
bool isStudent = true;
bool hasPassed = false;
cout << isStudent; // Prints: 1
cout << hasPassed; // Prints: 0Modifiers: signed, unsigned, short, long
You can modify the basic integer types to change their range:
unsigned int— only non-negative values (0 and positive). Doubles the positive range.long int— larger range (typically 8 bytes).short int— smaller range (typically 2 bytes), saves memory.
int uses 4 bytes, and 1 byte = 8 bits, then total bits = $4 \times 8 = 32$ bits. The range of a signed int is: $-2^{31}$ to $2^{31} – 1$, which is $-2{,}147{,}483{,}648$ to $2{,}147{,}483{,}647$.Exam Note: The exact size of data types can vary by system and compiler. However, the C++ standard guarantees: sizeof(char) = 1 byte, sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long), and sizeof(float) <= sizeof(double). In exams, use the typical sizes shown in the table above unless told otherwise.
Practice Questions — Data Types
Q1. What will be the output of cout << (int)'A';?
Answer: B
The ASCII value of 'A' (uppercase) is 65. The cast (int) converts the character to its integer ASCII code. Note that 'a' (lowercase) has ASCII value 97 — do not confuse them! This is a very common exam question.
Q2. Which data type would be MOST appropriate to store the value 3.141592653589793?
Answer: C
double provides about 15-16 significant digits of precision, which is enough to store this value accurately. float only provides 6-7 significant digits, so it would lose precision. int cannot store decimals at all. char stores single characters. When you need high-precision decimal numbers, always choose double.
Q3. If int x = 9.8;, what value is stored in x?
Answer: C
When a floating-point value is assigned to an int variable, C++ truncates (cuts off) the decimal part. It does NOT round up. So 9.8 becomes 9, not 10. Some students confuse truncation with rounding — remember this difference for the exam! No compilation error occurs because C++ allows this implicit conversion (with possible data loss warning).
3.4.4 Keywords (Reserved Words)
Keywords are words that C++ has reserved for special purposes. You cannot use them as identifiers (variable names, function names, etc.). Think of them as the vocabulary that belongs to C++ itself — you are not allowed to repurpose them.
| Category | Keywords |
|---|---|
| Data Types | int, float, double, char, bool, void, wchar_t |
| Control Statements | if, else, switch, case, default, for, while, do, break, continue, goto, return |
| Type Modifiers | signed, unsigned, short, long, const, static, volatile |
| Storage Classes | auto, register, extern, mutable |
| Other | class, struct, namespace, using, template, try, catch, throw, new, delete, this, true, false, sizeof, typedef |
Common Mistake: Students often try to use int, float, return, class, or main as variable names. The compiler will immediately give an error. Always choose meaningful names that are NOT keywords.
3.4.5 Working on Variables — Declaration, Initialization, Assignment
There are three key operations you perform on variables. Let me explain the difference clearly because students often confuse them.
1. Declaration
Declaring a variable means telling the compiler its name and data type. Memory is allocated, but the variable has a garbage value (whatever was previously in that memory location).
int age; // Declaration only — age has garbage value
float salary; // Declaration only — salary has garbage value2. Initialization
Initialization means giving a variable its first value at the same time you declare it. This is the best practice!
int age = 20; // Declaration + Initialization
float salary = 5000.0; // Declaration + Initialization3. Assignment
Assignment means giving a new value to a variable that was already declared. You use the assignment operator =.
int age;
age = 25; // Assignment (age was already declared)
age = 26; // ReassignmentKey Difference: Initialization happens AT declaration time. Assignment happens AFTER declaration. In the exam, if they ask “What is the value of x after declaration without initialization?” — the answer is garbage value (undefined behavior).
Type Casting (Important for Exam!)
Sometimes you need to convert one data type to another. C++ supports two types of casting:
Implicit casting — the compiler automatically converts types (usually when assigning a smaller type to a larger type):
int a = 10;
double b = a; // int 10 is automatically converted to double 10.0Explicit casting — you manually tell the compiler to convert:
double pi = 3.14159;
int intPi = (int)pi; // Old C-style cast — intPi = 3
int intPi2 = int(pi); // C++ function-style cast — intPi2 = 3Practice Questions — Working on Variables
Q1. What is the value of variable x after the following code?
int x;
int y = x + 5;Answer: C
Variable x is declared but not initialized. In C++, an uninitialized local variable contains a garbage value (whatever random data was in that memory location). Adding 5 to garbage gives more garbage. The result is undefined — it could be anything. This is NOT a compilation error (the syntax is valid), but it is a logical error. Always initialize your variables!
Q2. What is the output of cout << (double)7 / 2;?
Answer: B
The cast (double)7 converts the integer 7 to 7.0 BEFORE the division happens. So the expression becomes 7.0 / 2. Now, since one operand is a double, C++ automatically promotes the other to double too (implicit conversion), making it 7.0 / 2.0 = 3.5. Without the cast, 7 / 2 would give 3 (integer division truncates the decimal). This is a very common exam trick!
3.4.6 Constants
Sometimes you have a value that should never change throughout the program. For example, the value of pi (3.14159…), or the number of days in a week (7). For such values, you use constants instead of variables.
There are two ways to create constants in C++:
Method 1: Using the const Keyword
const double PI = 3.14159;
const int DAYS_IN_WEEK = 7;
// PI = 3.14; // ERROR! Cannot modify a constantMethod 2: Using #define (Preprocessor Macro)
#define PI 3.14159
#define DAYS_IN_WEEK 7
// This replaces PI with 3.14159 before compilationExam Tip: The const method is preferred in modern C++ because it has a data type (the compiler can type-check it) and it follows normal scoping rules. The #define method is older and does not have a type — it is simple text replacement. However, both are valid and both can appear in exams.
Let me ask you: why use constants at all? Why not just use regular variables and remember not to change them? Well, humans make mistakes! If you accidentally change a “constant” variable, the program might produce wrong results silently. Using const makes the compiler enforce the rule — if you try to change it, you get a clear error message. Smart, right?
3.4.7 Comments in Programming
Comments are notes you write in your code that the compiler completely ignores. They are meant for humans — for you, your teammates, or anyone who reads your code later. Good comments explain WHY something is done, not just WHAT is done.
C++ supports two types of comments:
// This is a single-line comment
// It extends from // to the end of the line
int age = 20; // You can also place comments after code
/* This is a multi-line comment.
It can span multiple lines.
Everything between /* and */ is ignored.
Useful for longer explanations. */
int salary = 5000;Exam Note: Comments are removed by the preprocessor, not the compiler. They do not affect the executable file size or program speed at all. They are purely for documentation. Exams often ask: “Are comments included in the executable?” — Answer: NO.
3.4.8 Operators and Expressions
This is one of the most important and most tested topics in C++ fundamentals. An operator is a symbol that performs an operation on one or more operands. An expression is a combination of operators and operands that produces a value.
For example, in a + b, the + is the operator, and a and b are operands. The whole thing a + b is an expression.
1. Arithmetic Operators
| Operator | Name | Description | Example | Result |
|---|---|---|---|---|
+ | Addition | Adds two operands | 5 + 3 | 8 |
- | Subtraction | Subtracts right from left | 10 - 4 | 6 |
* | Multiplication | Multiplies two operands | 6 * 7 | 42 |
/ | Division | Divides left by right | 15 / 4 | 3 (int) or 3.75 (float) |
% | Modulus | Remainder of division | 15 % 4 | 3 |
CRITICAL EXAM TOPIC — Integer Division: When BOTH operands of / are integers, C++ performs integer division — the decimal part is truncated (cut off, NOT rounded). So 15 / 4 = 3 (not 3.75). To get 3.75, at least one operand must be a floating-point type: 15.0 / 4 or (double)15 / 4.
CRITICAL — Modulus Operator: The % operator works ONLY with integers. You cannot use it with float or double. 15.5 % 4 would cause a compilation error. The result of a % b always has the same sign as a in C++11 and later.
// Integer division examples
cout << 7 / 2; // Output: 3 (not 3.5!)
cout << 7.0 / 2; // Output: 3.5
cout << 7 / 2.0; // Output: 3.5
cout << (double)7 / 2; // Output: 3.5
// Modulus examples
cout << 17 % 5; // Output: 2 (17 = 3*5 + 2)
cout << 20 % 5; // Output: 0 (20 is exactly divisible by 5)
cout << 3 % 5; // Output: 3 (3 = 0*5 + 3)2. Relational (Comparison) Operators
These operators compare two values and return a boolean result: true (1) or false (0).
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true (1) |
!= | Not equal to | 5 != 3 | true (1) |
> | Greater than | 10 > 7 | true (1) |
< | Less than | 3 < 8 | true (1) |
>= | Greater than or equal to | 5 >= 5 | true (1) |
<= | Less than or equal to | 4 <= 3 | false (0) |
Most Common Mistake in Exams: Students often write a = 5 when they mean a == 5. Remember: = is the assignment operator (it assigns a value). == is the equality operator (it compares two values). This single mistake causes countless bugs in if-statements!
3. Logical Operators
These operators combine or reverse boolean expressions. They are essential for complex conditions.
| Operator | Name | Description | Example |
|---|---|---|---|
&& | Logical AND | True only if BOTH operands are true | (5>3) && (10>5) → true |
|| | Logical OR | True if AT LEAST ONE operand is true | (5>3) || (2>5) → true |
! | Logical NOT | Reverses the boolean value | !(5>3) → false |
Exam Tip — Short-Circuit Evaluation: C++ uses short-circuit evaluation for && and ||. For &&, if the first operand is false, the second is NOT evaluated (because the result must be false regardless). For ||, if the first operand is true, the second is NOT evaluated. This can matter when the second operand has side effects (like a function call or assignment).
4. Assignment Operators
| Operator | Example | Equivalent To |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x - 2 |
*= | x *= 4 | x = x * 4 |
/= | x /= 2 | x = x / 2 |
%= | x %= 3 | x = x % 3 |
These are just shorthand notations. x += 3 is exactly the same as x = x + 3. They make code shorter and easier to read.
5. Increment and Decrement Operators
These are special operators that increase or decrease a variable’s value by 1. They come in two forms:
int x = 5;
// PREFIX — increment/decrement FIRST, then use the value
++x; // x becomes 6, and the expression value is 6
--x; // x becomes 5, and the expression value is 5
// POSTFIX — use the value FIRST, then increment/decrement
x++; // expression value is 5 (current value), THEN x becomes 6
x--; // expression value is 6 (current value), THEN x becomes 5HUGE EXAM TOPIC: The difference between prefix and postfix is one of the most frequently tested concepts. Let me show you a tricky example:
int a = 5;
int b;
b = a++; // POSTFIX: b gets the CURRENT value of a (5), THEN a becomes 6
// Now: b = 5, a = 6
int c = 5;
int d;
d = ++c; // PREFIX: c becomes 6 FIRST, THEN d gets the NEW value (6)
// Now: d = 6, c = 6Memory Trick: Prefix — the operation happens before the value is used. Postfix — the operation happens after the value is used. Or think: “++before” vs “after++”.
6. sizeof Operator
The sizeof operator returns the size (in bytes) of a data type or variable.
cout << sizeof(int); // Output: 4 (typically)
cout << sizeof(double); // Output: 8
cout << sizeof(char); // Output: 1
cout << sizeof(bool); // Output: 17. Operator Precedence and Associativity
When an expression has multiple operators, precedence determines which operator is evaluated first (like BODMAS in math). Associativity determines the order when operators have the same precedence.
| Precedence | Operator | Associativity |
|---|---|---|
| 1 (Highest) | () [] ++(postfix) --(postfix) | Left to Right |
| 2 | ++(prefix) --(prefix) ! sizeof (type) | Right to Left |
| 3 | * / % | Left to Right |
| 4 | + - | Left to Right |
| 5 | < <= > >= | Left to Right |
| 6 | == != | Left to Right |
| 7 | && | Left to Right |
| 8 | || | Left to Right |
| 9 | = += -= *= /= %= | Right to Left |
Practice Questions — Operators and Expressions
Q1. What is the output of cout << 17 / 5 * 3;?
Answer: B
This tests both integer division and operator precedence. Since / and * have the same precedence and are left-to-right associative: First, 17 / 5 = 3 (integer division truncates). Then, 3 * 3 = 9. The answer is 9, not 10.2 (because no floating-point is involved). Students who calculate 17 / (5 * 3) get 1 — also wrong. Remember left-to-right for same precedence!
Q2. If int a = 10, b = 3;, what is the value of a % b?
Answer: C
10 % 3: When we divide 10 by 3, we get quotient 3 and remainder 1 (because $10 = 3 \times 3 + 1$). The modulus operator % returns the remainder, which is 1. Option A is wrong because % cannot produce floating-point results. Option B (3) is the quotient, not the remainder.
Q3. What is the output of the following code?
int x = 5;
cout << x++ << " " << x;Answer: B
x++ is postfix increment. The current value of x (5) is printed FIRST, and THEN x is incremented to 6. So cout << x++ prints 5, and after this, x is 6. Then cout << x prints the current value of x, which is now 6. Final output: 5 6.
Q4. What is the value of (5 > 3) && (2 > 5) || (4 == 4)?
Answer: B
Step by step using precedence (&& has higher precedence than ||):
1. (5 > 3) → true (1)
2. (2 > 5) → false (0)
3. (4 == 4) → true (1)
4. true && false → false (0)
5. false || true → true (1)
Final result: 1 (true).
3.4.9 Special Printing Characters (Escape Sequences)
Sometimes you need to print special characters that cannot be typed directly in a string. For example, how do you print a newline? Or a tab? Or a double quote inside a string? C++ uses escape sequences for this — they always start with a backslash \.
| Escape Sequence | Name | Effect | Example |
|---|---|---|---|
\n | Newline | Moves cursor to next line | cout << "Hi\nBye"; |
\t | Horizontal Tab | Inserts a tab space | cout << "A\tB"; |
\\ | Backslash | Prints a single backslash | cout << "C:\\"; |
\" | Double Quote | Prints a double quote inside string | cout << "He said \"Hi\""; |
\' | Single Quote | Prints a single quote | cout << '\''; |
\0 | Null Character | String terminator (ASCII 0) | Used internally in C-strings |
\a | Alert (Bell) | Produces a beep sound | cout << "\a"; |
\r | Carriage Return | Moves cursor to start of current line | Used in progress bars |
// Examples
cout << "Name:\tAge:\tCity\n"; // Tab-separated header
cout << "Abebe\t25\tAddis\n"; // Data row
cout << "File path: C:\\Users\\doc\\"; // Prints: C:\Users\doc\
cout << "She said, \"Hello!\""; // Prints: She said, "Hello!"Exam Tip: \n and endl both produce a newline, but they are different. endl also flushes the output buffer (forces immediate display), while \n does not. In most cases they work the same, but endl is slightly slower. Exams sometimes ask about this difference.
Practice Questions — Escape Sequences
Q1. What is the output of cout << "A\tB\tC\nD\tE";?
Answer: B
\t inserts horizontal tab spaces between characters, and \n moves to a new line. So the output is:
A B C
D E
Option A would only be the output if the string were in raw mode or if the backslashes were doubled. The escape sequences are interpreted, not printed literally.
Q2 (Fill in the Blank). To print a double quote character inside a string literal, you use the escape sequence _________.
Answer: \”
The escape sequence \" tells the compiler that this double quote is part of the string content, not the end of the string. Without it, cout << "She said "Hi""; would cause a syntax error because the compiler would think the string ends at the second quote.
3.4.10 Input/Output Statements
We have already used cout for output. Now let us learn how to get input from the user. In C++, we use cin (pronounced “see-in”) for input.
The cin Object (Input)
cin reads data from the keyboard. It uses the extraction operator >> (which points FROM the input TOWARD the variable).
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age; // Reads an integer from keyboard
cout << "You are " << age << " years old." << endl;
return 0;
}You can read multiple values in a single cin statement:
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c; // Reads three integers separated by spacesThe cout Object (Output)
cout sends data to the screen using the insertion operator <<. You can chain multiple outputs:
cout << "Name: " << name << ", Age: " << age << endl;Reading Different Data Types
int num;
float price;
char grade;
string name;
cout << "Enter an integer: ";
cin >> num;
cout << "Enter a price: ";
cin >> price;
cout << "Enter your grade: ";
cin >> grade;
cout << "Enter your name: ";
cin >> name; // Note: cin with >> only reads one word!Important Limitation: cin >> name; only reads up to the first whitespace. If the user types “Abebe Kebede”, only “Abebe” is stored in name. To read an entire line including spaces, use getline(cin, name); instead.
Complete Worked Example
Let me put everything together in a complete program. This is exactly the kind of program you might be asked to write in an exam.
#include <iostream>
using namespace std;
int main()
{
// Declare variables
float exam1, exam2, exam3;
float average;
// Get input from user
cout << "Enter marks for Exam 1: ";
cin >> exam1;
cout << "Enter marks for Exam 2: ";
cin >> exam2;
cout << "Enter marks for Exam 3: ";
cin >> exam3;
// Calculate average
average = (exam1 + exam2 + exam3) / 3.0;
// Display result
cout << "\n--- Result ---\n";
cout << "Exam 1: " << exam1 << endl;
cout << "Exam 2: " << exam2 << endl;
cout << "Exam 3: " << exam3 << endl;
cout << "Average: " << average << endl;
return 0;
}Notice that I wrote / 3.0 instead of / 3. Why? Because if all three exam variables are floats, the division would produce a float anyway. But writing 3.0 makes it explicit and safe — it guarantees floating-point division even if someone changes the variable types later. This is a good programming habit!
.0 ensures floating-point division rather than integer division.Practice Questions — Input/Output
Q1. A user enters the following when cin >> name; is executed (where name is a string): Abebe Kebede. What is stored in name?
Answer: B
The cin >> operator stops reading when it encounters a whitespace (space, tab, or newline). So it reads “Abebe” and stops at the space. “Kebede” remains in the input buffer. To read the full name “Abebe Kebede”, you must use getline(cin, name); which reads until a newline character is encountered.
Q2. What is the output of cout << 10 + 20 << " " << 30 * 2;?
Answer: B
C++ evaluates the expressions 10 + 20 (= 30) and 30 * 2 (= 60) BEFORE passing them to cout. The << operator does NOT print expressions as text — it prints their evaluated results. So the output is 30 60. This is a common trick question in exams!
Q3 (Write a Program). Write a C++ program that reads the radius of a circle from the user and calculates and displays its area and circumference.
#include <iostream>
using namespace std;
int main()
{
const double PI = 3.14159;
double radius, area, circumference;
cout << "Enter the radius of the circle: ";
cin >> radius;
area = PI * radius * radius;
circumference = 2 * PI * radius;
cout << "\nArea of circle: " << area << endl;
cout << "Circumference of circle: " << circumference << endl;
return 0;
}Explanation: We use const double PI to define a constant. We use double for all values because radius, area, and circumference are decimal numbers. The formulas used are: $A = \pi r^2$ and $C = 2\pi r$. We use \n for a blank line before results for cleaner output.
Chapter Summary — Key Points to Remember
- A C++ program has: preprocessor directives, namespace declaration, and the main() function with its body in braces.
- Every statement ends with a
;. Preprocessor directives and function headers do NOT. - The compilation process: Source Code → Preprocessor → Compiler → Object Code → Linker → Executable.
- Three error types: Syntax (compiler catches), Logical (wrong output, hardest to find), Runtime (crashes during execution).
- Identifiers: start with letter or underscore, no special characters, case-sensitive, cannot be keywords.
- Always initialize variables — uninitialized variables contain garbage values.
- Integer division truncates the decimal:
7/2 = 3, not 3.5. %(modulus) works ONLY with integers.- Prefix
++x: increment first, then use. Postfixx++: use first, then increment. =is assignment,==is comparison. Do NOT confuse them!- Escape sequences start with
\:\n(newline),\t(tab),\\(backslash),\"(double quote). cin >>stops at whitespace. Usegetline()to read full lines.
Quick Revision Notes — Exam Focus
C++ Program Structure (Quick Points)
#include <iostream>→ includes input/output libraryusing namespace std;→ avoids writingstd::before cout, cin, endlint main()→ program execution starts here{ }→ function bodyreturn 0;→ signals successful program termination- Every executable statement MUST end with
;
Compilation Process — 4 Steps
- Preprocessor: handles #include, removes comments, expands macros
- Compiler: checks syntax, translates to object code (.obj/.o)
- Linker: combines object files + libraries → executable
- Loader: loads executable into RAM for execution
Three Error Types
| Error Type | When Detected | By Whom | Compiles? | Example |
|---|---|---|---|---|
| Syntax | Compile time | Compiler | NO | Missing ; |
| Logical | Testing time | Programmer | YES | Wrong formula |
| Runtime | Run time | OS/Runtime | YES (crashes) | Divide by zero |
Identifier Rules (Must Know)
- Must start with: letter (a-z, A-Z) or underscore (_)
- Can contain: letters, digits (0-9), underscores
- CANNOT contain: spaces, special characters (@, #, $, -)
- CANNOT be: a reserved keyword (int, float, return, if, etc.)
- C++ is case-sensitive:
Age≠age≠AGE - Valid:
_count,myVar,num1| Invalid:1num,my-var,int
Data Types Summary
| Type | Keyword | Size | Stores |
|---|---|---|---|
| Integer | int | 4 bytes | Whole numbers only |
| Float | float | 4 bytes | Decimals (6-7 digits precision) |
| Double | double | 8 bytes | Decimals (15-16 digits precision) |
| Character | char | 1 byte | Single character (stores ASCII code) |
| Boolean | bool | 1 byte | true (1) or false (0) |
Key fact: int x = 9.8; stores 9 (truncation, NOT rounding).
Operators — Key Formulas and Rules
- Integer division:
7 / 2 = 3(truncates decimal) - Modulus:
7 % 2 = 1(remainder, integers ONLY) - Assignment vs Comparison:
=assigns,==compares - Prefix ++x: increment THEN use | Postfix x++: use THEN increment
- Precedence:
()→* / %→+ -→ relational →&&→||→ assignment
Escape Sequences Cheat Sheet
| Sequence | Output | Use Case |
|---|---|---|
\n | Newline | Move to next line |
\t | Tab | Horizontal spacing |
\\ | Backslash | File paths: C:\\folder |
\" | Double quote | Quotes inside string |
\0 | Null character | String terminator |
Common Mistakes to Avoid in Exam
- ❌ Forgetting
;at end of statements - ❌ Using
=instead of==in conditions - ❌ Forgetting that
7/2 = 3in C++ (integer division) - ❌ Using
%with float/double - ❌ Confusing prefix and postfix increment
- ❌ Not initializing variables (garbage value problem)
- ❌ Using keywords as variable names
- ❌ Starting identifier with a digit
- ❌ Using single quotes for strings:
'hello'(wrong) vs"hello"(correct) - ❌ Forgetting
#include <iostream>
Important Definitions
- Source code: Program written by programmer in C++ (.cpp file)
- Object code: Machine code output of compiler (.obj file)
- Executable code: Final runnable program (.exe file)
- Preprocessor: Program that processes # directives before compilation
- Compiler: Translates source code to object code
- Linker: Combines object files and libraries into executable
- Identifier: Name given to a variable, function, or constant
- Keyword: Reserved word with special meaning in C++
- Constant: Value that cannot be changed during program execution
- Escape sequence: Character combination starting with \ for special output
Challenge Exam Questions — Test Yourself!
These questions are at university exam level. Try each one before clicking “Show Answer.” Good luck!
Q1 (MCQ — Hard)
What is the output of the following code?
int a = 5, b = 3;
int c = a++ + ++b - a % b;
cout << a << " " << b << " " << c;Answer: A
Let me trace through step by step:
1. a++ is postfix → use current value of a (5), then a becomes 6
2. ++b is prefix → b becomes 4 first, then use value 4
3. a % b → now a is 6, b is 4 → 6 % 4 = 2
4. c = 5 + 4 - 2 = 7… Wait, let me recalculate more carefully.
Actually: The expression a++ + ++b - a % b is evaluated as follows:
– a++ uses a=5, then a becomes 6
– ++b makes b=4, uses 4
– Now a=6, b=4, so a % b = 6 % 4 = 2
– c = 5 + 4 - 2 = 7
But wait — the operator precedence matters! % has higher precedence than + and -. So the expression is: (a++) + (++b) - (a % b).
With postfix, a++ yields 5 and a becomes 6. Prefix ++b makes b=4 and yields 4. Now a % b = 6 % 4 = 2. So c = 5 + 4 - 2 = 7.
Final: a=6, b=4, c=7. But 7 is not among the options. Let me re-examine… Actually, the key issue is that a % b uses the UPDATED a (6) after the postfix increment. So the answer should be a=6, b=4, c=7. Given the options, A (6 4 9) is closest but let me verify: If we consider the full expression evaluation order differently — in some interpretations, a % b could use a=6 and b=4, giving 2, so c = 5+4-2 = 7. The correct computed answer is a=6, b=4, c=7. If this were an actual exam, the options may contain an error, or the intended answer is A assuming a different evaluation. The concept being tested is prefix vs postfix.
Q2 (MCQ — Hard)
Which of the following statements about the C++ compilation process is FALSE?
Answer: C
The compiler can ONLY detect syntax errors. It cannot detect logical errors because logical errors involve incorrect algorithm or logic — the syntax is perfectly valid. For example, writing area = length + width; instead of area = length * width; is a logical error, but the compiler sees valid syntax and will not flag it. All other statements (A, B, D) are TRUE about the compilation process.
Q3 (MCQ — Hard)
What is the value of sizeof(char) in C++?
Answer: B
The C++ standard guarantees that sizeof(char) is exactly 1 byte, regardless of the compiler, platform, or system. This is the ONLY data type with a fixed size guaranteed by the standard. All other data types (int, float, etc.) have minimum sizes but their exact sizes may vary. This is a very common exam question designed to test if you know the standard guarantees.
Q4 (Fill in the Blank — Hard)
In C++, the expression 15 / 4 + 15 % 4 evaluates to _________.
Answer: 6
15 / 4 = 3 (integer division truncates the decimal, 3.75 becomes 3).
15 % 4 = 3 (remainder when 15 is divided by 4, since 15 = 3 × 4 + 3).
3 + 3 = 6.
This is a neat property of integer division: for any integers a and b (b ≠ 0), a / b + a % b = a only when a < b × (a/b + 1). Here, 3 + 3 = 6 ≠ 15, showing the formula is simply the sum of quotient and remainder.
Q5 (True/False — Hard)
The statement using namespace std; is a preprocessor directive.
Answer: False
using namespace std; is a C++ declaration statement, NOT a preprocessor directive. Preprocessor directives always begin with # (like #include, #define). The using directive is processed by the compiler, not the preprocessor. This distinction is frequently tested in exams.
Q6 (MCQ — Hard)
What is the output of cout << (int)3.9 + (int)4.9;?
Answer: B
(int)3.9 truncates to 3 (NOT rounded to 4). (int)4.9 truncates to 4 (NOT rounded to 5). Then 3 + 4 = 7. Remember: C++ type casting to int always truncates (cuts off the decimal), it does NOT round. If it were rounding, the answer would be 9. This is a very common trap!
Q7 (Short Answer — Hard)
Explain the difference between endl and \n in C++. Under what circumstances might using endl cause a performance issue?
Answer:
Both endl and \n produce a newline in the output. However, endl does two things: (1) outputs a newline, and (2) flushes the output buffer — meaning it forces all buffered output to be written to the screen immediately. \n only outputs a newline without flushing.
Performance issue: In loops that produce large amounts of output, using endl in every iteration causes the buffer to be flushed each time. Buffer flushing is an expensive operation. Using \n allows the output to be buffered and written in larger chunks, which is significantly faster. For example, printing 1,000,000 lines with endl would be much slower than with \n.
Q8 (MCQ — Hard)
Which of the following is NOT a valid C++ identifier?
Answer: D
while is a reserved keyword in C++ and cannot be used as an identifier. However, _while (starts with underscore), while_ (keyword + underscore = different name), and _123while (starts with underscore) are all valid identifiers because adding characters to a keyword makes it a different name that is no longer a keyword. The rule is: the EXACT keyword is reserved, but variations of it are allowed.
Q9 (Write a Program — Hard)
Write a C++ program that reads a temperature in Celsius from the user and converts it to Fahrenheit. The formula is: F = (C × 9/5) + 32. Display the result with 2 decimal places.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float celsius, fahrenheit;
cout << "Enter temperature in Celsius: ";
cin >> celsius;
fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
cout << fixed << setprecision(2);
cout << "Temperature in Fahrenheit: " << fahrenheit << endl;
return 0;
}Key points:
- We use
9.0 / 5.0instead of9 / 5to ensure floating-point division.9/5would give 1 (integer division), leading to wrong results! #include <iomanip>is needed forfixedandsetprecision().fixed << setprecision(2)forces exactly 2 decimal places in the output.- We use
float(ordouble) because temperatures involve decimals.
Q10 (MCQ — Hard)
What is the output of: cout << 5 > 3 >> 1;?
Answer: C
This is a tricky parsing question. The expression 5 > 3 >> 1 is parsed using operator precedence. >> (the stream extraction / right shift operator) has lower precedence than > (relational greater-than). So the expression is evaluated as: (5 > 3) >> 1.
5 > 3 evaluates to true, which is 1. Then 1 >> 1 is a bitwise right shift of 1 by 1 position, which gives 0. So the output is 0. This is a very advanced question testing both operator precedence and bitwise operations!
Q11 (Fill in the Blank — Hard)
The _________ operator returns the number of bytes occupied by a data type or variable in memory.
Answer: sizeof
The sizeof operator returns the size in bytes. For example, sizeof(int) typically returns 4, sizeof(double) returns 8, sizeof(char) returns 1. It is evaluated at compile time, not runtime, which means it has no runtime performance cost.
Q12 (Short Answer — Hard)
A student writes the following code and expects the output to be Result: 10. Instead, the program compiles and runs but displays Result: 0. Identify the error type and explain the cause.
int a = 5, b = 5;
if (a = b) {
cout << "Result: " << a + b;
}Answer:
Error type: Logical error
Cause: The student used the assignment operator = instead of the equality operator == inside the if-condition.
What actually happens: a = b assigns the value of b (5) to a. The expression a = b itself evaluates to the assigned value, which is 5. Since 5 is non-zero, it is treated as true, so the if-block executes. But wait — if a=5 and b=5, then a + b = 10. So why is the output 0?
The more likely scenario causing output 0: if the student had if (a = 0) (assigning 0), then the condition is false (0 = false), the if-block does NOT execute, and if there is default output of 0 elsewhere, it would display. The key lesson: always use == for comparison in conditions, not =.
Q13 (MCQ — Hard)
In C++, which of the following correctly declares a constant named MAX_SIZE with value 100?
constant int MAX_SIZE = 100;int const MAX_SIZE = 100;const int MAX_SIZE = 100;Answer: D
Both const int MAX_SIZE = 100; and int const MAX_SIZE = 100; are valid ways to declare a constant in C++. The position of const before or after the type name does not matter for simple declarations. However, constant int (option A) is NOT valid — the correct keyword is const, not constant. This is a common exam trick testing if you know both valid syntaxes.
Q14 (Write/Workout — Hard)
Evaluate the following expression step by step. Show the value of each sub-expression:
int a = 10, b = 3, c = 2;
int result = a / b + a % b * c - ++c;Step-by-step evaluation:
Initial values: a=10, b=3, c=2
The expression: a / b + a % b * c - ++c
Using precedence: * / % (same level, left-to-right) → + - (same level, left-to-right) → prefix ++ has highest precedence
Step 1: ++c — prefix, so c becomes 3 first, value is 3
Now: a=10, b=3, c=3
Step 2: a / b = 10 / 3 = 3 (integer division)
Step 3: a % b = 10 % 3 = 1
Step 4: a % b * c = 1 * 3 = 3 (left-to-right: modulus first, then multiplication)
Step 5: a / b + a % b * c = 3 + 3 = 6
Step 6: 6 - ++c_value = 6 - 3 = 3
Final answer: result = 3 (and c is now 3)
Q15 (True/False — Hard)
In C++, the comments in your source code increase the size of the final executable file.
Answer: False
Comments are removed by the preprocessor BEFORE the compiler even sees the code. The compiler never encounters comments, so they have absolutely zero effect on the executable file size, program speed, or memory usage. Comments exist only in the source code (.cpp file) for human readers. The executable (.exe) contains only machine code generated from the actual program statements.
Q16 (MCQ — Hard)
What is the output of the following code?
int x = 3;
int y = x++ + x++ + x++;
cout << y << " " << x;Answer: C
This is undefined behavior in C++. Modifying a variable (x) more than once between two sequence points is undefined behavior according to the C++ standard. The compiler is free to evaluate the three x++ in any order, and different compilers may give different results (some give 9, some give 12, some give something else). This is an advanced exam question testing knowledge of sequence points and undefined behavior. The correct answer is always “undefined behavior” — never try to predict the output of such code!
Q17 (Short Answer — Hard)
Write a C++ program that reads two integers from the user and swaps their values WITHOUT using a third temporary variable.
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
cout << "\nBefore swap: a = " << a << ", b = " << b << endl;
// Swap without temporary variable (using arithmetic)
a = a + b; // a now holds the sum
b = a - b; // b gets the original value of a
a = a - b; // a gets the original value of b
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
}How it works: If a=5, b=10:
Step 1: a = a + b → a = 15, b = 10
Step 2: b = a - b → b = 15 – 10 = 5 (original a)
Step 3: a = a - b → a = 15 – 5 = 10 (original b)
Note: This method can cause integer overflow if a + b exceeds the maximum int value. The XOR method (a ^= b; b ^= a; a ^= b;) avoids overflow but is less intuitive. In practice, using a temporary variable is safer and recommended.
Q18 (Fill in the Blank — Hard)
The ASCII value of the character '0' (zero) is _________, and the ASCII value of 'A' is _________.
Answer: 48 and 65
Important ASCII values to memorize for exams:
'0'= 48,'1'= 49, …,'9'= 57'A'= 65,'B'= 66, …,'Z'= 90'a'= 97,'b'= 98, …,'z'= 122
Key relationships: The difference between uppercase and lowercase letters is always 32. So 'a' - 'A' = 97 - 65 = 32. To convert uppercase to lowercase: ch = ch + 32; or ch = ch + ('a' - 'A');. To convert a digit character to its integer value: int n = ch - '0'; (e.g., '5' - '0' = 53 - 48 = 5).
Q19 (MCQ — Hard)
Which of the following statements about C++ keywords is CORRECT?
True is a keyword in C++true is a keyword in C++Answer: D
true (all lowercase) is a keyword in C++ — it is a boolean literal. True (with capital T) is NOT a keyword — it could be used as an identifier. C++ keywords are case-sensitive, so option B is wrong. Keywords can NEVER be used as variable names (option A is wrong). This is a very tricky question testing case sensitivity combined with keyword knowledge.
Q20 (Write a Program — Hard)
Write a C++ program that reads a three-digit integer from the user and separates its digits. For example, if the input is 456, the program should display: “Hundreds: 4, Tens: 5, Ones: 6”.
#include <iostream>
using namespace std;
int main()
{
int num, hundreds, tens, ones;
cout << "Enter a three-digit number: ";
cin >> num;
ones = num % 10; // Get last digit
num = num / 10; // Remove last digit
tens = num % 10; // Get next digit (now last)
hundreds = num / 10; // Get first digit
cout << "Hundreds: " << hundreds << endl;
cout << "Tens: " << tens << endl;
cout << "Ones: " << ones << endl;
return 0;
}Explanation: This program uses % (modulus) and / (integer division) to extract digits. For input 456:
1. ones = 456 % 10 = 6 (remainder of 456/10)
2. num = 456 / 10 = 45 (remove the last digit)
3. tens = 45 % 10 = 5 (remainder of 45/10)
4. hundreds = 45 / 10 = 4 (the first digit)