For Loop
C++ Programming Guide
Introduction to C++
Getting Started
Syntax and Comments
Output and Input
Variables
Data Types
Operators
Strings
Math and Booleans
If...Else
Switch Statement
While Loop
For Loop
Break and Continue
Arrays
Structures
Enums
References
Pointers
Functions
Function Parameters
Function Overloading
Scope
Recursion
Object-Oriented Programming
Classes and Objects
Class Methods
Constructors
Access Specifiers and Encapsulation
Inheritance
Polymorphism
File Handling
Exceptions
STL Basics
Common Mistakes
Practice Ideas
For Loop
C++ For Loop
Definition: The for loop is a robust control flow statement used to repeat a block of code a specific number of times. It is particularly effective when you know exactly how many iterations are required before the loop begins.
Why: In any beginner C++ guide, the for loop is introduced alongside other control statements as the most concise way to manage loops. By grouping the initialization, condition, and increment into a single line, it reduces code clutter and minimizes the risk of creating infinite loops.
Syntax Structure
The for loop consists of three distinct parts separated by semicolons within parentheses:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example: Printing a Sequence
In this example, the loop starts at 1, checks if the number is less than or equal to 5, and increments the value after every print statement:
#include <iostream> using namespace std; int main() { // The loop runs exactly 5 times for (int i = 1; i <= 5; i++) { cout << i << endl; } return 0; }
The Three Parameters of a For Loop
| Parameter | Execution Timing | Purpose |
|---|---|---|
| Initialization | Executed only once. | Sets the starting value of the loop counter (e.g., int i = 1). |
| Condition | Checked before every loop. | Evaluates to true or false. If false, the loop ends immediately. |
| Increment | Executed after every loop body. | Updates the counter (e.g., i++) to move toward the end condition. |
Key Notes
- Scope of the Counter: If you declare the variable
iinside the for loop (for(int i = 0...)), that variable only exists within the loop. It is destroyed once the loop finishes. - Nested Loops: You can place a
forloop inside anotherforloop. This is commonly used for working with multi-dimensional data like grids or tables. - Array Iteration:
forloops are the primary tool for traversing arrays. By using the counter as an index (array[i]), you can access every element in a list sequentially. - Infinite Loops: A
forloop can become infinite if the condition is omitted or can never be false, such asfor(;;). This is sometimes used in system programming but should be avoided by beginners.