Loops

My name is Sanford Ang. I am constructing this web page to fulfill requirements of my computer science class and to learn and help others learn about loops in JAVA. Any questions, comments, or corrections can be e-mailed to me at ironfist317@yahoo.com.

 

 

 

 

 

Introduction

When you program a computer to perform the same task repetitively it is a called a "loop". This web page takes a look at "while loops", “do loops”, “for loops”, and “for-each loops”.

 

“While loops”

A while loop consists of code and a condition. The condition is first evaluated - if the condition is true the code within the block is then executed. This repeats until the condition becomes false. “While loops” are also known as a pre-test loop.

 

An example of an “while loop” is in factorial

int counter = 5;
 long factorial = 1;
 while (counter > 0)
    factorial *= counter--; 

 

 

“Do Loops”

A do loop consists of code and a condition. First, the code within the block is executed, then the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Also known as a post-test loop.

 

The format of an “do loop” is

do {
  body-statements;
} while (test);
next-statement;
 
“For loops”
A for loop is distinguished by an explicit loop counter or loop variable. This allows the body of the for loop to know about the ordering of each repetition. For loops are also usually used when the number of repetitions is known before entering the loop.
 
The format of an “for loop” is
{
  initialization;
  while (test) {
    body-statements;
    increment;
  } 
}
 
An example of an problem for a “for loop” would be to create an factorial for it.
It can be solved in this way:
  public int factorial(int n)
 {
    int i;    
    int fact; 
    fact = 1;
    for (i = 1; i <= n; i++) 
{
      fact = fact * i;
    } 
    return fact;
  } 
 
 
“For-each loops”
For-each loops repeat the loop body for each value in a certain range or just repeat the loop body for each value in a collection of values.
 
The format for a “for-each loop” is
for (Type element : collection) 
{
  body-statements;
} 
 
An application in the real world of loops in JAVA would be in a video game. Loops in the code of video games are vital to a video game development because in video games, especially Role-playing games loops are useful when part of "What do I do next?" is to repeat the same thing several times to the user of the game when the user is being asked what does he want the character in the game to do.
 
 
 
Some interesting websites about loops are:
http://www.cs101.org/ipij/intro http://mat140.bham.ac.uk/~richard/msm2c/lectures/Iteration/    
http://en.wikipedia.org/wiki/While_loop 
http://en.wikipedia.org/wiki/Do_loop 
http://en.wikipedia.org/wiki/For_loop 
http://www.javacoffeebreak.com/articles/loopyjava/index.html 
http://www.sleepinggiantsoftware.com/FGJ/tutorials/tutorial_2/tutorial2_loopsinjava.htm