ITclub

العودة إلى C++
محاضرة 5

Loop Control (Break/Continue) and 1D Arrays

أوامر Break و Continue، والمصفوفات أحادية البعد

ملخص المحاضرة

📜 Lecture 5: Loops (Postfix/Prefix), Arrays (1D)

This lecture clarifies Postfix/Prefix inside cout, introduces break and continue, and covers 1D Arrays.

Key Concepts

  • Postfix/Prefix in cout:
    • cout << x++; (Postfix): Prints the current value of x, then increments x. Output of example is 3, then x becomes 4.
    • cout << ++x; (Prefix): Increments x first, then prints the new value. Output of example is 4.
  • Loop Control Statements: Used with for, while, and do-while loops.
    • break: Exits the loop immediately. In the example, the loop stops when i equals 5, so it only prints 0, 1, 2, 3, 4.
    • continue: Skips the rest of the current iteration and jumps to the next iteration. In the example, it skips i==3, so it prints 1, 2, 4.
  • 1D Arrays:
    • Benefit: Stores multiple values of the same data type in a single variable.
    • Syntax: data_type array_name[size];.
    • Declaration Methods:
      1. int x[5] = {1, 2, 3, 4, 5}; (Initialize with size).
      2. int x[5]; (Declare size, no values).
      3. int x[] = {1, 2, 3, 4, 5}; (Initialize without size; compiler figures it out).
    • Accessing Elements:
      • Indexing starts at 0.
      • The first element is x[0], the second is x[1], etc..
      • The last element of x[5] is x[4].
    • Accessing with Loops: A for loop is the standard way to iterate through an array. for (int i=0; i<3; i++) { cout << x[i] << endl; }.
    • Modifying Elements: You can change elements directly (e.g., x[i]++; or ++x[i];) inside a loop.