Szerkesztő:LinguisticMystic/cpp/For
🖥️ 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]- Run the initialization once.
- Check the condition.
- If
true, continue to the body. - If
false, exit the loop.
- If
- Execute the loop body.
- Run the modification.
- 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;→ initializeito 0.i < 10;→ loop as long asiis less than 10.i++→ increaseiby 1 after each iteration.std::cout << i << ' ';→ print the value ofi.
The variable
iexists 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 currentito thesumduring each loop.i <= 10000ensures 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
breakstatement 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
numberholds a copy of an element from the arraynumbers.
⚙️ Using auto for Simplicity
[szerkesztés]for (auto number : numbers) {
std::cout << number << " ";
}
autotells 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.