C--Loops

Loops

  Loops allow your programs to execute lines of code repeatedly saving you from needing to copy and paste or otherwise repeat lines of code. 

  C provides a few different ways to implement loops in your programs.

  while

    Use when you want a loop to repeat an unknown number of times,and possibly not at all.

    while (true)

    {

      statements;

    }

    This is what we call an infinite loop.The lines of code between the curly braces will execute repeatedly from top to bottom,until and unless we break out of it (as with a break;statement) or otherwise kill our program.

    while (boolean-expr)  // meanwhile, the while loop will continue to do it until it is false.

    {

      statements;

    }

    If the boolean-expr evaluates to true,all lines of code between the curly braces will execute repeatedly.In order from top-to-bottom,until boolean-expr evaluates to false.

    

  do-while

    Use when you want a loop to repeat an unknown number of times,but at least once.

    do

    {

      statements;

    }

    while (boolean-expr);

    This loop will execute all lines of code between the curly braces once,and then, if the boolean-expr evaluates to true,will go back and repeat that process until boolean-expr evaluates to false.

    This loop,unlike a while loop,is guaranteed to run at least one time.

  for

    Use when you want a loop to repeat a discrete number of times,though you may not know the number at the moment the program is compiled.

    for (int i = 0;i < 10;i++)

    {

      statements;

    }

    Syntactically unattractive,but for loops are used to repeat the body of a loop a specified number of times,in this example 10.

    The process undertaken in a for loop is:

      if it evaluates to true,the body of the loop executes.

      if it evaluates to false,the body of the loop does not execute.

    The counter variable is incremented,and then the Boolean expression is checked again,etc.

猜你喜欢

转载自www.cnblogs.com/jllin/p/9927134.html