Loop - C Tutorial

Loop

A loop in a computer program is an instruction that repeats until a specified condition is reached. In a loop structure, the loop asks a question. If the answer requires an action, it is executed. The same question is asked again and again until no further action is required. Each time the question is asked is called an iteration.

A computer programmer who needs to use the same lines of code many times in a program can use a loop to save time.

Types of Loops

  • A while loop is a loop that is repeated as long as an expression is true. An expression is a statement that has a value.
  • A do while loop or repeat until loop repeats until an expression becomes false.
  • A for loop is a loop that runs for a preset number of times.
  • An infinite or endless loop is a loop that repeats indefinitely because it has no terminating condition, the exit condition is never met or the loop is instructed to start over from the beginning.
  • A nested loop appears inside any other for, while or do while loop

A goto statement can create a loop by jumping backward to a label, although this is generally discouraged as a bad programming practice. For some complex code, it allows a jump to a common exit point that simplifies the code.

Loop Control Statements

A statement that alters the execution of a loop from its designated sequence is a loop control statement.

C#, for example, provides two loop control statements.

  • A break statement inside a loop terminates the loop immediately.
  • A continue statement jumps to the next iteration of the loop, skipping any code in between.