Lokang 

C++ and MySQL

for

The for loop is one of the most commonly used control flow structures in C++. It is ideal for situations where you know in advance how many times you want to iterate over a block of code. The for loop is concise and versatile, allowing you to control the initialization, condition, and iteration all in one line.

The Structure of a for Loop

The basic syntax of a for loop in C++ is as follows:

for (initialization; condition; increment/decrement) {
   // Code to execute on each iteration
}
  • initialization: This is where you initialize your loop control variable. It is executed only once at the beginning of the loop.
  • condition: This is a boolean expression that is checked before each iteration of the loop. If the condition is true, the loop body executes; if false, the loop terminates.
  • increment/decrement: This is where you update your loop control variable. It is executed after each iteration of the loop body.

Example 1: Basic for Loop

Let’s start with a simple example where a for loop is used to print numbers from 1 to 5.

#include <iostream>
using namespace std;
int main() {
   for (int i = 1; i <= 5; i++) {
       cout << i << endl;
   }
   return 0;
}

Explanation:

  • Initialization: int i = 1; sets the loop control variable i to 1.
  • Condition: i <= 5; checks if i is less than or equal to 5.
  • Increment: i++ increments i by 1 after each iteration.
  • The loop prints the values 1 through 5, one per line.

Example 2: Looping Through an Array

A for loop is often used to iterate over the elements of an array.

#include <iostream>
using namespace std;
int main() {
   int numbers[] = {10, 20, 30, 40, 50};
   for (int i = 0; i < 5; i++) {
       cout << "Element at index " << i << " is: " << numbers[i] << endl;
   }
   return 0;
}

Explanation:

  • The array numbers[] contains 5 elements.
  • The loop starts at index 0 and runs until i < 5 (i.e., for indices 0 through 4).
  • It prints each element of the array with its corresponding index.

Example 3: Nested for Loops

You can nest for loops within each other to handle more complex tasks, such as iterating over a 2D array or generating a multiplication table.

#include <iostream>
using namespace std;
int main() {
   for (int i = 1; i <= 3; i++) {
       for (int j = 1; j <= 3; j++) {
           cout << i << " * " << j << " = " << i * j << endl;
       }
       cout << endl; // Print a new line after each inner loop
   }
   return 0;
}

Explanation:

  • The outer loop (i) runs 3 times.
  • For each iteration of the outer loop, the inner loop (j) also runs 3 times.
  • The program prints a multiplication table for numbers 1 through 3.

Example 4: Modifying the Control Variables

You can modify the initialization, condition, and increment parts of the for loop to achieve different behaviors.

Counting Downwards

#include <iostream>
using namespace std;
int main() {
   for (int i = 5; i >= 1; i--) {
       cout << i << endl;
   }
   return 0;
}

Explanation:

  • Initialization: int i = 5; starts the loop with i set to 5.
  • Condition: i >= 1; checks if i is greater than or equal to 1.
  • Decrement: i-- decreases i by 1 after each iteration.
  • The loop counts down from 5 to 1.

Example 5: Skipping Iterations with continue

You can use the continue statement inside a for loop to skip the rest of the current iteration and move on to the next one.

#include <iostream>
using namespace std;
int main() {
   for (int i = 1; i <= 5; i++) {
       if (i == 3) {
           continue; // Skip the rest of the loop when i == 3
       }
       cout << i << endl;
   }
   return 0;
}

Explanation:

  • The loop prints the numbers 1, 2, 4, and 5.
  • When i == 3, the continue statement causes the loop to skip printing the number 3.

Example 6: Exiting a Loop Early with break

The break statement can be used to exit the loop immediately, regardless of the loop condition.

#include <iostream>
using namespace std;
int main() {
   for (int i = 1; i <= 5; i++) {
       if (i == 4) {
           break; // Exit the loop when i == 4
       }
       cout << i << endl;
   }
   return 0;
}

Explanation:

  • The loop prints the numbers 1, 2, and 3.
  • When i == 4, the break statement causes the loop to terminate.

When to Use a for Loop

  • Known Number of Iterations: When you know in advance how many times you want to iterate.
  • Array and Container Traversal: When you need to iterate over arrays or containers like vectors.
  • Nested Iterations: When dealing with multi-dimensional structures such as 2D arrays.

Comparison with Other Loops

  • while loop: Use when the number of iterations is not known beforehand, and the loop should continue until a certain condition is met.
  • do-while loop: Use when you want the loop body to execute at least once before checking the condition.

Summary

  • The for loop is versatile and concise, allowing you to manage the initialization, condition, and iteration of the loop control variable in one place.
  • It’s ideal for situations where the number of iterations is known in advance.
  • The loop can be easily modified for various scenarios, including counting up or down, skipping iterations, and breaking out of the loop early.

This content provides a detailed explanation of the for loop in C++, including examples, when to use it, and practice problems to help reinforce the understanding of this essential loop structure.