Unit 1 Introduction to C++
Unit 1 Introduction to C++
• What is the result if we replace the first for statement with the
following?
for (i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*
Summary
Use switch for Fixed Values : Switch is ideal for comparing a variable against fixed
values.
switch (choice) {
case 1: cout << "Option 1"; break;
default: cout << "Invalid choice"; break;
}
Programming Tips for Conditional Statements
Avoid Deep Nesting : Refactor nested conditions to improve readability.
Use Ternary Operator : For simple conditions, use the ternary operator.
if (x > 0) {
cout << "Positive";
}
if (x > 0) {
cout << "Positive";
}
Programming Tips for Conditional Statements
Use Constants for Magic Numbers : Use named constants instead of hard-coded values.
if (number < 0) {
cout << "Negative";
}
Programming Tips for Looping Statements
Choose the Right Loop : Use `for`, `while`, and `do-while` loops appropriately based
on the scenario.
Use `while` for Conditional Loops : `While` is ideal when the number of iterations
isn't known beforehand.
while (condition) {
cout << "Running loop";
condition = false;
}
Use `do-while` for At Least One Iteration : `Do-while` ensures the block executes at
least once.
do {
cout << "Executed once";
} while (condition);
Programming Tips for Looping Statements
Use Break and Continue Wisely : Use `break` to exit a loop early and `continue` to
skip the current iteration.
Use Constants for Loop Limits : Avoid hard-coded values in loop conditions.