In this article we will learn about C++ for loop, The C++ for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop than while or do-while loops.
The C++ for loop is same as C/C#. We can initialize variable, check condition and increment/decrement value.
C++ for Loop structure
for(initialization; condition; update){ //code to be executed }
Here,
initialization
– initializes variables and is executed only oncecondition
– iftrue
, the body offor
loop is executed
iffalse
, the for loop is terminatedupdate
– updates the value of initialized variables and again checks the condition
C++ for Loop example
#include <iostream> using namespace std; int main() { for(int i=1;i<=10;i++){ cout<<i <<"\n"; } }
Output:
1 2 3 4 5 6 7 8 9 10