Definition of a Loop

The loop is one of the three basic structures of computer programming

binary code with circles

metamorworks/Getty Images

Loops are among the most basic and powerful of programming concepts. 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 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.

Just about every programming language includes the concept of a loop. High-level programs accommodate several types of loops. C, C++, and C# are all high-level computer programs and have the capacity to use several types of loops.

Types of Loops

  • A for loop is a loop that runs for a preset number of times.
  • 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.
  • 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. Although it is possible for a programmer to intentionally use an infinite loop, they are often mistakes made by new programmers.
  • 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.

Basic Structures of Computer Programming

Loop, selection, and sequence are the three basic structures of computer programming. These three logic structures are used in combination to form algorithms for solving any logic problem. This process is called structured programming.

 

 

 

Format
mla apa chicago
Your Citation
Bolton, David. "Definition of a Loop." ThoughtCo, Jul. 30, 2021, thoughtco.com/definition-of-loop-958105. Bolton, David. (2021, July 30). Definition of a Loop. Retrieved from https://www.thoughtco.com/definition-of-loop-958105 Bolton, David. "Definition of a Loop." ThoughtCo. https://www.thoughtco.com/definition-of-loop-958105 (accessed March 19, 2024).