C++/changing a for loop to a while loop
Expert: vijayan - 11/25/2008
QuestionHi,
I was told that we should be able to make a while loop from a for loop, is that true?
I have tried to change the following code:
bool operator==(const Vector & v)const{
if(size!=v.size){
return false;
}
for(int i=0;i<size;i++){
if(val[i]!=v[i]
return false;
}
return true;
}
now using a while loop instead:
bool operator==(const Vector & v)const{
if(size!=v.size){
return false;
}
int i;
while (i<size){
if(val[i]!=v[i]
return false;
}
return true;
}
is that correct? could we use "return" for while loops as well?
thank you
Answerthe for statement provides a compact way to iterate over a range of values.
programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied.
the general form of the for statement can be expressed as follows:
for( initialization ; condition ; increment )
{
loop body statement(s)
}
the initialization expression is executed once, right in the beginning.
condition expression is evaluated before each time the loop body is executed; if it evaluates to false, the loop terminates.
the increment expression is evaluated after each iteration through the loop; though it is usually an increment of the loop counter, it can be any valid expression.
the while statement continually executes a block of statements as long as a particular condition is true.
its syntax can be expressed as:
while( expression )
{
loop body statement(s)
}
the while statement evaluates expression each time through the loop.
if it evaluates to true, the loop body statement(s) are executed.
the while statement continues testing the expression and executing its block until the expression evaluates to false.
therefore, a for-loop
for( initialization ; condition ; increment )
{
for-loop body statement(s)
}
can be converted to a while-loop by writing:
initialization ;
while( condition )
{
for-loop body statement(s)
increment ;
}
in our example, the for-loop is
for( int i=0 /*initialization*/ ; i<size /*condition*/ ; i++ /*increment*/ )
{
if( val[i] != v[i] ) return false ; /*for-loop body statement*/
}
an the equivalent while-loop would be
int i = 0 ; /*initialization*/
while( i<size ) /*condition*/
{
if( val[i] != v[i] ) return false ; /*for-loop body statement*/
i++ ; /*increment*/
}
> is that correct?
no, in your code, you forgot the initialization and the increment.
> could we use "return" for while loops as well?
certainly yes. anything you could use in the for-loop body could also be used in the while loop