Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

for and while loops

 
Khurram Hussain
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
which loop is more efficient? for loop or while loop
 
Michael Fitzmaurice
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Khurram
What do you mean by 'efficient'? If you are seeking to learn how to use just one and stick to it because it's 'more efficient', that won't work.
The while loop obviously just checks if a condition is true or false, if true then the code of the loop is executed. A for loop normally declares and initialises a variable, checks a condition, if true executes the code of the loop, then typically increments or decrements a counter.
In this respect, you could say it is carrying out more 'work' outside of the block of code in the loop, so 'less efficient'. However, the point is, you would normally use them for slightly differnt purposes, and the logic required would be the overriding factor in deciding which one to use.

------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley
 
timothy zimmerman
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Khurram,
As Michael said the factor that should determine which looping method you use depends on what it is you are tyring to accomplish.
The for loop is typically controlled by a counter (although you could use differently) so you might use it when you know how any times you want to repeat logic within the loop (ie you want to list the contents of an Array).
int numberOfIterations = myArray.length;
for( int counter = 0; counter < numberOfIterations; counter++)
{
// statements
}
The while loop evaluates a given expression and if it is true executes the code within the loop while that condition remains true. This would be useful if you don't know how many times you will need to execute the loop. One example of this would be the run() method. You would want to continue looping until some condition dictates otherwise.
run()
{
keepRunning = true;
while( keepRunning
{
// whatever you want do do while running
// loop keeps executing until the value of keepRunning changes
}
)

There is also the do while loop. This is very similar to the while loop execpt that the logical expression is evaluated at the end of the loop rather than the beginning. This means that the code within the loop will be executed at least once even if the condition is false.
do
{
// statements
}
while( expression )
Hope this helps.
 
Dan Lund
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i use just for loop`s just sometimes while loop`s...........
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic