The increment operator ++
increases its operand by 1.
The decrement operator --
decreases its operand by 1.
Postfix Mode: num++
(increments variable after its value is used).
Prefix Mode: ++num
(increments variable before its value is used).
Examples:
num = num + 1
num += 1
num = num - 1
num -= 1
When using cout
, the placement of ++
matters:
Postfix: cout << num++
will display the original value before incrementing.
Prefix: cout << ++num
will display the incremented value.
Important in expressions involving multiple operations.
Loops repeat a certain block of code as long as a condition is true.
In C++, there are three main types of loops: while
, do-while
, and for
.
Syntax:
while(condition) {
// code to execute
}
The condition is evaluated before the loop executes. If it's false, the loop won't execute.
int number = 0;
while (number < 5) {
cout << "Hello\n";
number++;
}
Using while
for input validation keeps asking the user until valid input is received.
Example:
int num;
cout << "Enter a number (1-100): ";
cin >> num;
while (num < 1 || num > 100) {
cout << "Invalid number! Enter a valid number: ";
cin >> num;
}
A loop inside another loop is called a nested loop. Each inner loop runs completely for every iteration of the outer loop.
Useful in scenarios like creating tables or complex conditions.
The do-while
loop checks its condition after executing the loop body, ensuring the loop runs at least once.
Syntax:
do {
// code to execute
} while(condition);
Ideal when the number of iterations is known in advance.
Syntax:
for(initialization; condition; update) {
// code to execute
}
The loop is a pretest loop; it checks the condition before each iteration.
for(int i = 0; i < 10; i++) {
// code
}
Counter: A variable that increments on each loop iteration.
Accumulator: A variable that accumulates totals (e.g., a sum).
Example:
int total = 0;
for (int i = 0; i < 10; i++) {
total += i;
}
Working with file streams (ifstream for input, ofstream for output).
Necessary for saving data.
Open the file.
Process the file (read/write).
Close the file.
Use the <fstream>
header for file operations.
Text Files: Human-readable (ASCII/Unicode).
Binary Files: Not human-readable (stored in binary format).
A sentinel is a value that marks the end of a list (e.g., -1
to end input).
Useful for loops that process unknown amounts of data.
This study guide covers the increment/decrement operators, various loop structures, processing data with files, and input validation. Make sure to practice writing these in a coding environment to solidify your understanding!