Home >>C++ Tutorial >C++ For Loop
In order to iterate a part of the program numerous times, the For loop in C++ is used. It is generally recommended to use the For loop instead of while or do-while loop when the number of iterations are certain/predefined. The programmers can check conditions, increment/decrement value and initialize the variable in C++ by using the For loop.
Here is the syntax of the For loop in C++
for(initialization; condition; incr/decr) { //code to be executed }
Here is an example of the For loop(Print 1 to 10)
#include <iostream> using namespace std; int main() { for(int i=1;i<=10;i++) { cout<<i<<"\n"; } }
Here is another example of the For loop(Print all even number from 1 to 100)
#include <iostream> using namespace std; int main() { for(int i=1;i<=100;i++) { if(i%2==0) { cout<<i<<" "; } } }
Here is another example of the For loop(Print the sum of even and odd number from 1 to 100)
#include <iostream> using namespace std; int main() { int even=0; int odd=0; for(int i=1;i<=100;i++) { if(i%2==0) { even=even+i; } else { odd=odd+i; } } cout<<"Sum of even="<<even<<"\n"; cout<<"Sum of odd="<<odd; }
A For loop can be used inside another For loop and it is called as the Nested For loop in C++ programming. Whenever the outer loop that is created gets executed once then the inner loop gets executed completely. For instance if the inner and outer loop are executed for 3 times then the inner loop will be executed 3 times for each outer loop that will be 9 times in total.
Here is an example of the nested For loop in the C++ programming:
#include <iostream> using namespace std; int main () { for(int i=1;i<=2;i++) { for(int j=1;j<=2;j++) { cout<<i<<" "<<j<<"\n"; } } }
Here is another example of the nested For loop to print Triangle:
#include <iostream> using namespace std; int main () { for(int i=1;i<=3;i++) { for(int j=1;j<=i;j++) { cout<<" * "; } cout<<"\n"; } }
Here is another example of the nested For loop
#include <iostream> using namespace std; int main () { for(int i=1;i<=3;i++) { for(int j=1;j<=3;j++) { cout<<i; } cout<<"\n"; } }
Here is another example of the nested For loop
#include <iostream> using namespace std; int main () { for(int i=1;i<=3;i++) { for(int j=1;j<=i;j++) { cout<<j; } cout<<"\n"; } }