For Loop
Loop executes the same block of code again and again until the given condition is true.
for(statement-1 ; statement-2 ; statement-3)
{
...
}
Statement-1 – assign value to a variable.
Statement-2 – check condition.
Statement-3 – change the value of variable.
forLoop.cpp
#include <iostream>
using namespace std;
int main(){
int i;
for(i=0; i<5; i++){
cout<<”My name is Joseph”<<endl;
}
return 0;
}
This will print name 5 times.
Dry Run:
- Statement-1 shows i=0. Statement-2 checks the condition, i is less than 5(true), move inside loop and print name.
- Statement-3 will increment i, now i=1. Statement-2 will check the condition, i is less than 5(true), move inside loop and print name.
- Statement-3 will increment i, now i=2. Statement-2 checks the condition i is less than 5(true), move inside loop and print name.
- Statement-3 will increment i, now i=3. Statement-2 checks the condition i is less than 5(true), move inside loop and print name.
- Statement-3 will increment i, now i=4. Statement-2 will check the condition i is less than 5(true), move inside loop and print name.
- Statement-3 will increment i, now i=5. Statement-2 will check the condition i is less than 5(false), loop will terminate and control moves to next line.
forLoop.cpp
#include <iostream>
using namespace std;
int main(){
int i;
for(i=0; i<5; i++){
cout<<i<<endl;
}
return 0;
}
Nested Loops:
Nested loops are loops within loops. When we have a nested loops then, when outer loop runs one-time, inner loops complete its all iterations. After that control moves to the outer loop. Again, the outer loop runs a second time and inner loop completes its all iterations. This process will continue until the outer loop completes its all iterations.forLoop.cpp
#include <iostream>
using namespace std;
int main(){
for(int i=0 ; i<5 ; i++){
cout<<"Outer loop running"
for(int j=0 ; j<5 ; j++){
cout<<"Inner loop running";
}
}
return 0;
}
Infinite for loop:
If you put the double semicolon inside paranthesis, it will become infinite for loop.// infinite for loop
for(;;){
// code
}