محاضرة 4
Conditional Statements and Loops
التحكم في تدفق البرنامج (if, else, for, while)
ملخص المحاضرة
📜 Lecture 4: Control Flow (If, Else, Loops)
This lecture introduces decision-making (if/else) and the three main types of loops (for, while, do-while).
Key Concepts
ifStatement: Executes a block of code only if a condition (a boolean expression) istrue.if (condition) { ... }
else ifStatement: Used to check a new condition if the firstifwasfalse. You can have multipleelse ifblocks.elseStatement: Executes a block of code if all precedingifandelse ifconditions werefalse.- Example (Even/Odd):
if (num % 2 == 0) { cout << "Even"; } else { cout << "Odd"; }. - Nested
if: Anifstatement can be placed inside anotherifstatement. This is shown as a solution to correctly identify0separately from other even numbers.
- Example (Even/Odd):
- Loops: Used to repeat a block of code until a condition is met.
forLoop: Used when you know (or can calculate) the number of iterations.- Syntax:
for (initialization; condition test; increment or decrement) { ... }. - Example (Count 1 to 5):
for (int i=1; i<=5; i++) { ... }. - Example (Count 5 to 0):
for (int i=5; i>=0; i--) { ... }.
- Syntax:
whileLoop: Used when you loop based on a condition, and the number of iterations is unknown.- Syntax: The condition is checked before each loop.
initialization; while(condition) { // block of code update; // e.g., i++ }
- Syntax: The condition is checked before each loop.
do-whileLoop: Similar towhile, but the condition is checked after the loop.- Syntax:
do { ... } while(condition);. - This loop is guaranteed to run at least once.
- Syntax:
محتويات المحاضرة
اختبر فهمك للمحاضرة
تصحيح فوري بالذكاء الاصطناعي