feature-language – difference between while and for

Question:

What's the difference between while and for , if they're both repeating loops, if with both I can do the same things either condition a stop or variable iterations, because both exist. My doubt is:

  1. Is there a way to demonstrate that one is better than the other?
  2. Is there any situation where only one responds to the case?

Answer:

Here is a scientific article that deals only with this comparison. Furthermore, performance clearly depends on the particular application and the language compiler used.

In C# , FOR is a little faster. FOR teve uma média de 2,95-3,02 ms . The While média de cerca de 3,05-3,37 ms . Run the code yourself and see:

class Program
    {
        static void Main(string[] args)
        {
            int max = 1000000000;
            Stopwatch stopWatch = new Stopwatch();

            if (args.Length == 1 && args[0].ToString() == "While")
            {
                Console.WriteLine("While Loop: ");
                stopWatch.Start();
                WhileLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
            else
            {
                Console.WriteLine("For Loop: ");
                stopWatch.Start();
                ForLoop(max);
                stopWatch.Stop();
                DisplayElapsedTime(stopWatch.Elapsed);
            }
        }

        private static void WhileLoop(int max)
        {
            int i = 0;
            while (i <= max)
            {
                //Console.WriteLine(i);
                i++;
            };
        }

        private static void ForLoop(int max)
        {
            for (int i = 0; i <= max; i++)
            {
                //Console.WriteLine(i);
            }
        }

        private static void DisplayElapsedTime(TimeSpan ts)
        {
            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);
            Console.WriteLine(elapsedTime, "RunTime");
        }
    }

The for loop is generally used when you know the number of iterations beforehand. For example to iterate through an array of 10 elements you can loop and increment the counter 0-9 (or 1 a 10 ). while other hand is used when you have an idea about the range of values ​​in which to iterate, but don't know the exact number of iterations that occur. for example:

while (!algumaCondicao()){
     // Remove elemento (s)
     // Adiciona elemento (s)
}

Here we don't know exactly how many times the loop will be executed.

Furthermore, FOR is more of a convenience than a language builder. For example, a FOR easily be expanded in a while loop.

for ( c=0; c<10; c++ ) is equivalent to:

c=0;
while ( c<10 ) {
  // alguns códigos loucos aqui
  c++;
}

Also, FOR is not limited to simple numerical operations, you can do more complex things like this (C syntax):

// uma lista encadeada simples
struct node {
  struct node *next;
};
struct node; // declarando nosso nó

//iterar sobre todos os nós a partir do nó 'start' (não declarado neste exemplo)
for ( node=start; node; node=node->next ) {}

The result is an iteration over a simple linked list.

You can also have multiple initializers, conditions, and instructions (depending on the language) such as: for(c = 0, d = 5; c <10, d <20; c ++, d ++).

Scroll to Top