الانتقال إلى المحتوى الرئيسي
eLearner.app
الوحدة 2 · الدرس 2 من 35/18 في الدورة~12 min
دروس الوحدة (2/3)

الحلقات

Loops allow repeating the execution of a block of code as long as a condition remains true.

In C++, the standard loops are: for, while, and do-while.

The for Loop

The for loop is used when you know the number of iterations in advance:

Code
// Prints numbers from 0 to 4
for (int i = 0; i < 5; ++i) {
    std::cout << i << " ";
}

The structure of the for loop is split into three parts separated by semicolons ;:

  1. Initialization: run only once at the beginning (e.g. int i = 0).
  2. Condition: evaluated before each iteration; if false, the loop ends (e.g. i < 5).
  3. Update: run at the end of each iteration (e.g. ++i).

The while Loop

The while loop repeats the code as long as its condition is true. It is typically used when the number of iterations is not known beforehand:

Code
int energy = 3;
while (energy > 0) {
    std::cout << "Energy: " << energy << std::endl;
    energy--; // Decrement to prevent an infinite loop
}

The do-while Loop

Unlike the while loop, the do-while loop guarantees that the body of the loop is executed at least once, because the condition is evaluated at the end:

Code
int x = 10;
do {
    std::cout << "Executed!" << std::endl;
} while (x < 5); // Condition is false, loop terminates after the first iteration

Try it yourself

تمرين#cpp.m2.l2.e1
المحاولات: 0جارٍ التحميل…

Print numbers from 1 to 5 inclusive, one at a time, using a for loop.

جارٍ تحميل المحرر…
إظهار التلميح

Use the syntax `for (int i = 1; i <= 5; ++i) { ... }`.

الحل متاح بعد 3 من المحاولات

تمرين#cpp.m2.l2.e2
المحاولات: 0جارٍ التحميل…

Given count = 5, use a while loop to print count and decrement it as long as it is greater than 0.

جارٍ تحميل المحرر…
إظهار التلميح

Usa `while (count > 0) { ... }`and don't forget to decrement`count--` inside the loop.

الحل متاح بعد 3 من المحاولات