মূল কন্টেন্টে যান
eLearner.app
মডিউল 2 · 2-এর পাঠ 3কোর্সে 5/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 প্রচেষ্টার পরে উপলব্ধ