Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/For

A Wikiszótárból, a nyitott szótárból

🖥️ What Makes Computers So Wonderful?

[szerkesztés]

Computers excel at processing data quickly and handling repetitive tasks tirelessly. Imagine having to print all 26 letters of the alphabet or even thousands of values one by one. Doing this manually would be inefficient, time-consuming, and frustrating. Thankfully, programming provides us with loops — structures that let us automate such repetition with ease.

One of the most popular loops used in C++ (and many other languages) is the for loop. It allows us to run a block of code multiple times in a controlled manner — ideal for iterating through arrays, ranges, or performing tasks a specific number of times.



🔁 Basic for Loop Syntax

[szerkesztés]
for (initialization; condition; modification) {
    // statements to execute repeatedly
}

🔍 Explanation of Each Part:

[szerkesztés]
  • Initialization: Executed once before the loop starts. Often used to declare and initialize a loop counter.
  • Condition: Evaluated before each iteration. If it evaluates to false, the loop stops.
  • Modification: Executed after each loop iteration to update the loop control variable.



🧭 Execution Flow of a for Loop

[szerkesztés]
  1. Run the initialization once.
  2. Check the condition.
    • If true, continue to the body.
    • If false, exit the loop.
  3. Execute the loop body.
  4. Run the modification.
  5. Go back to step 2.



🧪 Example 1: Printing Numbers from 0 to 9

[szerkesztés]
#include <iostream>

int main() {
    for (int i = 0; i < 10; i++) {
        std::cout << i << ' ';
    }
    return 0;
}

🧾 Output:

[szerkesztés]
0 1 2 3 4 5 6 7 8 9

📘 Explanation:

[szerkesztés]
  • int i = 0; → initialize i to 0.
  • i < 10; → loop as long as i is less than 10.
  • i++ → increase i by 1 after each iteration.
  • std::cout << i << ' '; → print the value of i.

The variable i exists only inside the loop unless declared outside.


🧪 Example 2: Calculating the Sum of Numbers 1 to 10000

[szerkesztés]
#include <iostream>

int main() {
    int sum = 0;

    for (int i = 1; i <= 10000; i++) {
        sum += i;
    }

    std::cout << "The sum is: " << sum << std::endl;
    return 0;
}

🧾 Output:

[szerkesztés]
The sum is: 50005000

📘 Explanation:

[szerkesztés]
  • sum += i; → adds the current i to the sum during each loop.
  • i <= 10000 ensures that the number 10000 is included.



🧪 Example 3: Printing the Alphabet in Groups of Four

[szerkesztés]
#include <iostream>

int main() {
    char alphabet[] = {
        'A','B','C','D','E','F','G','H','I','J','K','L','M',
        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    };

    int alphabetSize = sizeof(alphabet) / sizeof(alphabet[0]);
    int lettersPerLine = 4;

    for (int i = 0; i < alphabetSize; i++) {
        std::cout << alphabet[i] << ' ';
        if ((i + 1) % lettersPerLine == 0) {
            std::cout << '\n';
        }
    }

    return 0;
}

📘 Explanation:

[szerkesztés]
  • Calculates the array size using sizeof(alphabet) / sizeof(alphabet[0]).
  • Prints 4 letters per line by checking (i + 1) % lettersPerLine == 0.



🔄 Optional Parts in for Loops

[szerkesztés]

You can omit one or more parts of the loop:

🔸 Example: Initialization Outside the Loop

[szerkesztés]
int i = 10;
for (; i > 0; i--) {
    std::cout << i << " ";
}

🔸 Infinite Loop

[szerkesztés]
for (;;) {
    // Infinite loop unless broken manually
}

⚠️ Be careful with infinite loops — they run forever unless you use a break statement or an exit condition inside the loop.


🔁 Nested Loops

[szerkesztés]

You can place a loop inside another to handle multi-dimensional data, like grids or tables.

🧪 Example: Multiplication Table (1 to 9)

[szerkesztés]
#include <iostream>

int main() {
    for (int i = 1; i < 10; i++) {
        for (int j = 1; j < 10; j++) {
            std::cout << i * j << "\t";
        }
        std::cout << std::endl;
    }
    return 0;
}

🧾 Output:

[szerkesztés]
1	2	3	...	9
2	4	6	...	18
...
9	18	27	...	81

Nested loops multiply each pair of numbers and print them in tabular form.


⚠️ Off-by-One Errors

[szerkesztés]

These occur when:

  • The loop runs one time too many or too few.
  • Common mistakes: using < instead of <=, starting at the wrong index, or incorrect updates.

✅ Best Practice:

[szerkesztés]

Always test loops with:

  • Zero iterations
  • One iteration
  • Multiple iterations



🧵 Range-Based for Loops (C++11 and Later)

[szerkesztés]

🔸 Syntax:

[szerkesztés]
for (element : collection) {
    // use element directly
}

🧪 Example:

[szerkesztés]
#include <iostream>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};

    for (int number : numbers) {
        std::cout << number << " ";
    }

    return 0;
}

Each number holds a copy of an element from the array numbers.


⚙️ Using auto for Simplicity

[szerkesztés]
for (auto number : numbers) {
    std::cout << number << " ";
}
  • auto tells the compiler to infer the type of each element.
  • Reduces mistakes and keeps the code clean.



🧾 Summary

[szerkesztés]
Feature Traditional for Loop Range-Based for Loop
Best For Indexed access Iterating all elements
Index Access Yes No
Flexibility High Moderate
Verbosity More Less
C++ Version All C++11+



🧠 Final Thoughts

[szerkesztés]

Mastering for loops helps you:

  • Avoid code repetition.
  • Automate complex tasks.
  • Work with arrays, strings, matrices, and containers.
  • Build more efficient and cleaner code.

Tip: When debugging loop issues, print loop variables and check loop bounds. A clear understanding of when and how your loop runs will save you time and frustration.