0
Please explain the concept of for loop in c++??
2 Answers
+ 3
The for loop works this way :
for ( variable; condition; Math-Operator )
{
//Code
}
When the system reaches the for loop, it will create the 'variable' , test the 'condition' in the variable. If the condition is met, it will process the 'Code' and once it is done with the 'Code', it will proceed with the 'Math-Operator'. Then it will go back to testing the 'condition' again... This will stop once the 'condition' is not met or failed.
For example :
for (int x = 0; x < 10; x++)
{
cout<<"spam"<<endl;
}
/*The code above will write the word 'spam' 9 times on the console.*/
Do note that the 'variable' and 'Math-Operator' part can be ignored if you prefer to write it down on your own like a while loop. For example :
int x = 5;
for (; x != 0;)
{
cout<<x<<endl;
x = x-1;
}
/*The code above will write a value of 5-1 on the console.*/
0
thank you