ITclub

العودة إلى C++
محاضرة 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

  • if Statement: Executes a block of code only if a condition (a boolean expression) is true.
    • if (condition) { ... }
  • else if Statement: Used to check a new condition if the first if was false. You can have multiple else if blocks.
  • else Statement: Executes a block of code if all preceding if and else if conditions were false.
    • Example (Even/Odd): if (num % 2 == 0) { cout << "Even"; } else { cout << "Odd"; }.
    • Nested if: An if statement can be placed inside another if statement. This is shown as a solution to correctly identify 0 separately from other even numbers.
  • Loops: Used to repeat a block of code until a condition is met.
  • for Loop: 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--) { ... }.
  • while Loop: 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++ }
  • do-while Loop: Similar to while, but the condition is checked after the loop.
    • Syntax: do { ... } while(condition);.
    • This loop is guaranteed to run at least once.