For in C++
for
is C++’s primary looping construct, but it also supports while
and do-while
loops. Here are some basic types of loops in C++.
The most basic type is a while
loop with a single condition.
A classic for
loop in C++ has three components: initialization, condition, and iteration.
C++11 introduced range-based for loops, which can be used to iterate over elements in an array, vector, or other container.
C++ also supports infinite loops using while(true)
or for(;;)
. You can use break
to exit the loop or return
to exit the function.
You can use continue
to skip to the next iteration of the loop.
To run the program, save it as for_example.cpp
and compile it using a C++ compiler:
C++ offers various looping constructs, and we’ll see more examples when we look at containers, algorithms, and other data structures.