0
Why we should we use forloop
3 Réponses
+ 5
So you don't have to repeat the instructions.
+ 1
to repeat a part of code specific times or to loop through all iterators or elements of an array.
For example to find if a number is inside a array, we should use a for loop
+ 1
I don't think "should" be the right word here ...
The choice is up to the scenario (and the coder) no one is to say we should use a for-loop.
However, IMO a for-loop preference over the do-while-loop or the while-loop was due to the feasibility of declaration and use of loop scoped variables. This ensures that the loop scoped variables are only recognized within the loop body and loop construct.
Example
// in main function
int i{ 1024 };
for( int i{ 1 }; i <= 10; i++ )
{
std::cout << i << std::endl;
}
std::cout << i << std::endl;
You can see we have two variable definitions equallly identified by the name <i>. The first <i> definition is outside the loop (initialized to 1024), and the second <i> definition is inside loop construct (initialized to 1). The change made by incrementing value of the <i> inside the loop will not affect the <i> defined outside the loop.
This loop scoped variable feature was not available in other types of loop. So prefer for-loop when you want to isolate variables availability within the loop only.