Difference between while and for

Asked

Viewed 17,275 times

20

What’s the difference between while and for, if the two are loops of repetition, if with the two I can do the same things either conditioning a halt or iterations of variable, because there are both. My question is:

  1. There is a way to show that one is better than the other?
  2. Is there any situation where only one attends the case?
  • 3

    It is a pity that the answer accepted is not really authored by the author and not only does not cite the source, it does not have the date that was made. The information may be out of date. In my tests, that’s not what happened. I think I’ll answer at least to complement this.

8 answers

16


Here has a scientific article that deals only with this comparison. Moreover, the performance clearly depends on the applying in particular and the compiler of the language 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 noose for is usually used when you know the number of iterations beforehand. For example to scroll 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 make 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 don’t know exactly how many times the loop will run.

In addition, the FOR is more of a convenience than a language constructor. For example, a FOR be easily expanded into 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, O 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 chained list.

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

13

In my view, the 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 (i.e., stop when the variable reaches x). In pseudocode:

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

I don’t know if you can say that one is better than the other, but in cases where you need a cycle based on the value of a counter, it’s worth using the for than do on nail with while, simply because it takes less work and becomes clearer at first glance.

Similarly, if you need an infinite loop of the kind while(true), it makes no sense to use a for, that is made for finite loops. At the bottom it makes no sense to use for if you don’t need an accountant, since it is based on this.

11

There is a way to show that one is better than the other?

Usually the while is used while a certain condition is not met. Example:

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

As the for is usually used when iterating a data string. 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 the hand with either of the two achieving the same result as if you were using it with the other, but there is usually a more appropriate choice between the two that you will achieve 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 any situation where only one attends the case?

No. Always you will achieve the same result, the difference is the work you will spend to achieve it.

For ways of simplifying work, in some languages still has the foreach sometimes called for avançado.

Example in Java:

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
?>

8

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

Has language that only has the for. If you think about it, you don’t need more than this.

It has also been said that it depends on the application, the compiler, but it depends on the environment as well. At least this is what explains the conclusion that the accepted answer has arrived (which by the way has been plagiarized from here since it does not cite the source). There it showed that the for is faster than the while. I put the code of both more simply since I wasn’t going to measure the time. I’m going to show the CIL code of both and I’m not going to tell you what the for and what is the while, try to find out. And see if you can find any reason for one to be faster than the other.

To help: the instruction NOP does absolutely nothing, spends no time, it serves for alignment or space reserve 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 compiler version. As far as I know in optimized C the generated code is also the same. Most languages in most implementations should be like this. I can’t imagine why it wouldn’t be in most situations.

I even understand differences when compared to foreach.

That page on Wikibooks may be of interest.

5

Both work well, but what you use will depend on your requirements.

for will execute the instructions through a known sequence for (i = 0; i < 10; i++) - traverse lists, vectors, execute a defined number x of shares and other.

As the while will execute the instructions until the condition(s) (s) is(m) met(s) 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 they enter "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);
}

3

A while is a more simplistic form for a loop of repetition, where in its structure one has 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 the 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.*/
}

3

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

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
--------------------------------------------------

Completion

for provides you with resources for pre-initialization (run before performing the loop), validating and processing (last processing).
while provides you with the validation feature.
Remembering that both are ties, it will depend on you choose which one to use, as to what is the difference between: for(;TRUE;) and while(TRUE)?

2

Has its differences:

I use the for to manipulate vectors and while when I wish to stay in a looping until something happens.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.