Title: Loops
Course: COP1000: Introduction to Programming > Section: Module Ten

Introduction

A loop is a sequence of statements that is specified once but that may be carried out several times in succession. The code "inside" the loop is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely. (http://en.wikipedia.org/wiki/Loop_%28computing%29#Loops)

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement. The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loop checks the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

Syntax is as follows: (http://en.wikipedia.org/wiki/While_loop)
repeat
xxx
until test;

do
xxx
while (test);

In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement. Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished by an explicit loop counter or loop variable. This allows the body of the for loop to know about the sequencing of each iteration. For loops are also typically used when the number of iterations is known before entering the loop. For loops are the shorthand way to make loops when the number of iterations is known.  For loops are often used with arrays to process all the items.

The syntax of a for loop follows: (http://en.wikipedia.org/wiki/For_loop)
for a determined number of times:
do Something

The same tasks can be accomplished with each loop. The reason each type exists is because it makes programming a certain way easier. Technically only one type of loop ever needs to be used.

Objectives

Upon completion of this module, the student will be able to:

Define the following: "WHILE LOOPS", "DO/WHILE LOOPS", "FOR LOOPS"
Recognize the syntax of a loop statement
Implement a loop inside a program
Assess the use of the different loops inside of a program

Readings & Resources

Chapter 4: Guess the Number p. 41
Chapter 9: Hangman p. 121-127