C++ For statement - learn CPP, The for clause uses repetition to perform a certain command several times. An important note before starting you should know that in C++ language if we put in front of the variable (++), the variable will increase by one, which means that if the number is 5 and we put in front of the variable (++) it will become 6.
For commands that need to be repeated, they are placed in the body of the loop.
The for clause needs a counter from which the rotation begins and a number to end in order to run the cycles and the amount of increment.
the general syntax of the for clause:
If it is one sentence then its form is:
for (vari_delcration ; condition ; increment/decrement)
statement;
We don't need to add parentheses.
If it is more than one sentence, we must add the brackets {}, and the general formula is:
for (vari_delcration; condition ; increment/decrement)
{
statement 1;
statement 2;
...
}
First: for is one of the reserved words and indicates the beginning of repetition.
Second: we take what is between the parentheses after for which is the following line:
(vari_delcration; condition ; increment/decrement)
We divide the previous line into three parts, after each semicolon ( ;) we will find the following:
The first part (vari_delcration): In this part, the variable is declared and given an initial value.
The second part (condition): Is the condition for repetition. If the condition is fulfilled, the repetition stops, and if it is not met, it continues.
The last part is (increment/decrement): It means the amount of increment to be added to the variable or the amount of decrement.
Third: Statement: These are the commands to be executed within the iteration loop.
Explanation of the previous words with a simple example:
What does the following line (int j=0;j<=4;j++) mean?
j <= 4 means that when j becomes less than or equal to 4 it stops repeating.
(j++) means add 1 to j each time.
In this case, the repetition will be from 1 to 4.
Note: the value of j will change each time iterates.
For example, if we set int i = 9 and set the term i <= 19, here the iteration will be from 9 to 19.
Apply to the for clause:
Example printing the numbers 0 to 10.
#include<iostream>
using namespace std;
int main()
{
for(int j=0;j<=10;j++)
}
count<<j<<endl;
}
}
We initially defined a variable as an integer j and gave it the value 0, and set the condition that the loop stops when the value of j becomes less or equal to 10. If the condition is not met, the program will continue to output the value of j and the value of j will increase by one after each cycle.