Looping

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

Kaboodleloop.png

A loop is a control structure that is written once but may execute zero, one, or more times in a row. It controls the flow of the program, allowing the program to cycle back to the beginning of the loop and execute the code it contains again. To accomplish this a test condition is placed usually placed at the beginning of the code block, although in one instance, the condition is at the end. When the test condition is at the beginning, it is tested every time before the code inside the loop executes. If it is at the end, it will be tested after the code in the loop executes. Once the test fails the program continues on to any code found after the loop.

Life Without Loops

As an example, think about a program that requires the user to input ten numbers. With the tools we have up to now, we would end up with a program that looks something like:

 String input;
int input1, input2, input3, input4, input5, input6, input7, input8, input9, input10;

input = JOptionPane.showInputDialog("Enter number 1:");
input1 = Integer.parseInt(input);

input = JOptionPane.showInputDialog("Enter number 2:");
input2 = Integer.parseInt(input);

// etc...

input = JOptionPane.showInputDialog("Enter number 10:");
input10 = Integer.parseInt(input); 

This program has (at least) two problems:

  1. Writing the code is repetitive: you have to write the same block of code (with minor changes) ten times.
  2. The code is not general purpose: in order to modify your code to accept, say, the numbers 11-20 instead of 1-10, you'd have to go and change each occurence in your code.

In order to write code that fixes these two problems, we will study loops.

Summary

A loop will generally start with conditions placed at the beginning of the code block. They can be similar to if statements, and are boolean conditions that tell the program when to stop executing the code in the loop. The block of code within the loop will follow this statement, surrounded by a "{" at the start and a "}" at the end so the program knows the boundaries of the loop. The most common types of loops are the while loop and for loop. The first type of loop we will examine is the while loop.

Previous Page: Control Structures Next Page: While Loops