Difference between while and for

17

What is the difference between while and for , if both are loop repeats, if with both I can do the same things either condition a stop or variable iterations because there are both. My question is:

  • Is there a way to demonstrate that one is better than the other?
  • Is there a situation where only one answers the case?
  • asked by anonymous 05.05.2015 / 21:47

    8 answers

    13

    Here has a scientific article that deals only with this comparison. In addition, the performance clearly depends on the application in particular and the compiler of the language used.

    In C# , FOR is a bit 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 usually used when you know the number of iterations beforehand. For example to walk through an array of 10 elements that you can use to loop and increment the counter 0-9 (or 1 a 10 ). On the other hand while is used when you have an idea about the range of values in which to do an iteration, but do not know the exact number of iterations that occur. for example:

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

    Here we do not know exactly how many times the loop will be executed.

    In addition, FOR is more a convenience than a language constructor. For example, a FOR can be easily 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++;
    }
    

    In addition,% w / o% is not limited to simple numeric 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) as such: FOR

        
    05.05.2015 / 22:03
    11

    In my understanding, for is syntactic sugar for a common use case of while , which is to use a variable as a counter and a condition based on the value of that variable (that is, stop when the variable arrives at x ). In pseudocode:

    int i = 0;
    while(i < 10) {
       // faz algo
       i++;
    }
    

    I do not know if one can say that one is better than the other, but in cases where a cycle based on the value of a counter is needed, it is worthwhile to use the for of what to do on the nail with% simply because it gives less work and gets clearer at first glance.

    Similarly, if you need an infinite loop of type while , it does not make sense to use a while(true) , which is done for finite loops. In the background it does not make sense to use for if you do not need a counter, since it is based on that.

        
    05.05.2015 / 21:56
    9
      

    Is there a way to demonstrate that one is better than the other?

    Usually% w / w% is used while a particular condition is not met. Example:

    boolean continua = true;
    while(continua) {
        //alguma lógica...
        continua = checaSeDesejaContinuar();
    }
    

    While while is usually used when you want to iterate a data stream. Example:

    int[] notas = new int[10];
    for(int i=0; i<10; i++) {
        notas[i] = leProximaNota();
    }
    

    Of course, it is possible to make a repeat loop in hand with either of the two reaching the same result as if you were using the other, but there is usually a more appropriate choice between the two that you will reach the goal with less work . Example:

    boolean continua = true;
    for(; continua;) {
        //alguma lógica...
        continua = checaSeDesejaContinuar();
    }
    

    and

    int[] notas = new int[10];
    int i = 0;
    while(i<10) {
        notas[i] = leProximaNota();
        i++;
    }
    
      

    Is there a situation where only one responds?

    No. You will always achieve the same result, the difference is the work you will take to achieve it.

    For simplifying work, some languages still have for sometimes called foreach .

    Java example:

    int[] notas = new int[]{1, 2, 5, 2, 10};
    for(int n: notas) {
        System.out.println(n);
    }
    

    Example in PHP:

    <?php
    $arr = array(1, 2, 3, 4);
    foreach ($arr as &$value) {
        $value = $value * 2;
    }
    // $arr is now array(2, 4, 6, 8)
    unset($value); // break the reference with the last element
    ?>
    
        
    05.05.2015 / 22:01
    7

    It has already been said that the basic difference is the semantics you want to give the code. When for was invented it was more limited to giving a numerical sequence. When they invented giving him more flexibility, he started to compete more directly with while , although he was already competing in some situations.

    It has language that only has for . If you think about it, you do not need it.

    It has also been said that it depends on the application, the compiler. But it depends on the environment too. At least this is what explains the conclusion that the accepted answer has arrived (which by the way has been plagiarized from here ). It showed that for is faster than while . I put the code of both in a simplified way since I was not going to measure the time. I'll show the CIL code of both and I will not tell you what for and what while , try to find out. And see if you find any reason for one being faster than the other.

    To help: NOP does nothing, does not spend time, it serves to align or reserve space for later use, among other utilities.

    IL_0000:  nop
    IL_0001:  ldc.i4.0
    IL_0002:  stloc.0
    IL_0003:  br.s       IL_000d
    
    IL_0005:  nop
    IL_0006:  ldloc.0
    IL_0007:  stloc.1
    IL_0008:  ldloc.1
    IL_0009:  ldc.i4.1
    IL_000a:  add
    IL_000b:  stloc.0
    IL_000c:  nop
    IL_000d:  ldloc.0
    IL_000e:  ldc.i4     0x2710
    IL_0013:  cgt
    IL_0015:  ldc.i4.0
    IL_0016:  ceq
    IL_0018:  stloc.2
    IL_0019:  ldloc.2
    IL_001a:  brtrue.s   IL_0005
    
    IL_001c:  nop
    IL_001d:  ret
    

    The other

    IL_0000:  nop
    IL_0001:  ldc.i4.0
    IL_0002:  stloc.0
    IL_0003:  br.s       IL_000d
    
    IL_0005:  nop
    IL_0006:  nop
    IL_0007:  ldloc.0
    IL_0008:  stloc.1
    IL_0009:  ldloc.1
    IL_000a:  ldc.i4.1
    IL_000b:  add
    IL_000c:  stloc.0
    IL_000d:  ldloc.0
    IL_000e:  ldc.i4     0x2710
    IL_0013:  cgt
    IL_0015:  ldc.i4.0
    IL_0016:  ceq
    IL_0018:  stloc.2
    IL_0019:  ldloc.2
    IL_001a:  brtrue.s   IL_0005
    
    IL_001c:  ret
    

    Of course this may be different in another language, in another version of the compiler. As far as I know in optimized C the generated code is also equal. Most languages in most implementations should look like this. I can not imagine why it would not be in most situations.

    I even understand differences when compared to foreach .

    This page on WikiBooks might interest you.

        
    05.08.2015 / 14:15
    5

    The two work well, but which one to use will depend on your requirements.

    for will execute the statements through a known sequence for (i = 0; i < 10; i++) - scroll lists, vectors, execute a set number x actions and others.

    While while will execute the statements until the condition (s) is (are) met while (check) .

    In many cases you can do the same thing using the 2, for example, an algorithm that records the user's products until he enters "close" to complete the purchase.

    Example in Java using while

    Scanner scan = new Scanner(System.in);
    ArrayList<String> carrinho = new ArrayList<String>();
    
    while (pedido != "fechar") {
        pedido = scan.nextLine();
        carrinho.add(pedido);
    }
    

    Example in Java using for

    Scanner scan = new Scanner(System.in);
    ArrayList<String> carrinho = new ArrayList<String>();
    int i = 0, y = 0;
    
    for (i = 0; y < 10; i++) {
        pedido = scan.nextLine();
    
        if (pedido == "fechar") {
            break;
        }
    
        carrinho.add(pedido);
    }
    
        
    05.05.2015 / 22:04
    3

    A while is a more simplistic form for a loop of repetition, where in its structure there is only the condition.

    Example:

    while(condição){
      //Bloco que será executado enquanto condição satisfaça (Ou seja o valor lógico seja true)
    }
    

    A for is a more complex structure than while . In this we can determine the initialization of a variable. Then we determine the condition and, finally, we can increment a variable. Usually these three parameters are related:

    for(int i = 0; i<10; i++){
        /*Este bloco será executado enquanto a variável definida "i" não alcançar o
        número limite estipulado no segundo parametro "i<10" o ultimo parametro 
        trata de incrementar o "i" a cada interação.*/
    }
    
        
    05.05.2015 / 22:02
    3

    First to know how to distinguish the two you need to know what its elements are:

    For

    for (expr1; expr2; expr3)
        statement
    
        expr1   =   Executada uma vez incondicionalmente no incio do ciclo
        expr2   =   Avaliado no inicio de cada iteração, se TRUE o loop continua, se FALSE o loop termina
        expr3   =   Executado no final de cada iteração
    

    Examples

    --------------------------------------------------
    for(int k = 0; k < 10; k++)
        #   Inicia a varivel k  (lembrando que ele so executa o 1º argumento 1 vez)
        #   Avalia k
        #   Processa o incremento de k
    
    --------------------------------------------------
    int *k; 
    
    for(; k != NULL; k->prox)
        # Note que o 1º argumento foi omitido
        # Avalia k
        # k recebe o próximo ponteiro (lembrando que ele executa sempre no final o 3º argumento)
    
    --------------------------------------------------
    for(; (k % 10) != 1;){
        k = rand()%100;
    
        if((k % 3) == 0){
            k += 27;
        }
    
        if((k % 2) == 1){
            k += 8;
        }
    }
    
        # Note que o 1º argumento note foi omitido
        # Avalia a expressão
        # Note que o 3º argumento note foi omitido, ou seja o iteração de k depende no contexto do 'for'
    --------------------------------------------------  
    

    While

    while (expr):
        statement
        ...
    endwhile;
        expr    =   Avaliado no inicio de cada iteração, se TRUE o loop continua, se FALSE o loop termina
    

    Examples

    --------------------------------------------------
    while(true)
        # Note que a expressão sempre é TRUE, ou seja vai permenecer no while eternamente, 
          a menos que haja um 'break' no meio do 'statement'
    --------------------------------------------------
    while(false)
        # Note que a expressão é FALSE, ou seja nem vai entrar no while
    --------------------------------------------------
    int p = 5, k = 3, j = 12;
    
    while(p == 5 && k == 3 || j != 10)
        # Avalia o resultado da expressão
    --------------------------------------------------
    int p = 5, k = 3, j = 12;
    
    while(p = k - j)
        # Avalia o resultado da expressão
    --------------------------------------------------
    

    Conclusion

    for provides you with resources for pre-initiation (execute before looping), validate and process (last processing). while gives you the ability to validate. Remembering that both are ties, it will depend on you to choose which one to use, why is the difference between: for(;TRUE;) and while(TRUE) ?

        
    06.05.2015 / 02:34
    2

    It has its differences:

    I use for to handle vectors and while when I want to stay in a loop until something happens.

        
    05.05.2015 / 22:15