You can call for as simplified version of while. When "while" only use condition inside parentheses, you can put three statement. There are first value of a variable, condition, and variable changes. Here is the syntax.
- for(first_value;condition;arithmetic_operations)statement;f
- for(first_value;condition;arithmetic_operations){statement1;statement2;//other statements}
Example :
#include <iostream>
using namespace std;
int main(){
int numr;
for(numr=1;numr<=10;numr++){
cout << numr << endl;
}
cout << "finished";
return 0;
}
Example :
1 2 3 4 5 6 7 8 9 10 finished
That code has similar output with the code that you can see below.
#include <iostream>
using namespace std;
int main(){
int numr=1;
while(numr<=10){
cout << numr << endl;
numr++;
}
cout << "finished";
return 0;
}
Example :
1 2 3 4 5 6 7 8 9 10 finished
While or for loop will be repeated as long as condition is true.