for (;n!=0;n/=10)
{
  do something till n==0;
}

Is this something like a while loop or do while loop or some kind of imitation?

Dawood Ahmad commented: for loop +0

Recommended Answers

All 4 Replies

A for loop without an intitialisation. The intitialisation is probably done before the loop. Yes you could say is is like a while.

The for loop has these part, for(initialize counter;set condition that while true the loop will run;set increment). In your example the counter(n) is already initialized so that part is skipped. The loop will run as long as the counter(n) is not 0. In each iteration of the loop the counter(n) is divided by 10.

You can do the same thing with a while/do while loop. However the different parts may need to be coded separately

while(n!=0)
{
    //do something
    n /= 10;
}

Typically when you know the limits of your loop and the code needs to use the value of the counter the for loop will work better, for example iterating through an array. However when the limit is unknown and you don't need a counter value a while/do while loop will usually work better, for example reading a file.

Just to put my nose in...Unless you need to use the counter variable outside the for loop (which in my opinion is bad practice in nearly all cases) you should initialise the counter value in the loop declaration. It ensures that the counter can only be modified in the scope of your loop and is tidier memory management for the GC.

EDIT: This is still the case even if your counter value comes from external sources.

/* Bad IMO */
int counter = HelperClass.GetNumberOfItems();
for(;counter != 0;counter--)
{
}

/* Better IMO */
for(int counter = HelperClass.GetNumberOfItems(); counter != 0; count--)
{
}
// or
int numberOfItems = HelperClass.GetNumberOfItems();
for(int counter = numberOfItems; counter != 0; counter--)
{
}

/* Never EVER use public fields/properties
 * Especially true in threaded applications
 * You're pretty much asking for trouble :P
 */
for(; this.NumberOfItems != 0; this.NumberOfItems--)
{
}

Like tinstaafl, I'd only use a while loop when checking a specific condition where an index/counter isn't required.

So; while(dataReader.Read()){ /* Use datareader */ }
Not;

int n = 0;
while(n < 10)
{
    Console.WriteLine(item[n].DisplayName);
    n++;
}
commented: Great clarification! +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.