
Using Different Loops
So far we've only seen programs
that run each statements only once. Thus, using loops let us execute
the same statements more than once. Loops are very common in writing programs to
get inputs from
users, do something with the input, then get more input from the user and do
something with it again.
Like if
statements loops rely on conditional expressions to tell them when to get out of
the loop. If we
don't have conditional expressions loops would run on forever. Infinite loops
are useful too, the windows
we are running, it's a very good example of infinite loop.
Lets start with the famous
for loop
with our example.
The basic principle behind a for loop
is that the loop itself maintains a
counter variable, a variable's value
increases each time the body of the loop is executed
The basic format of a for loop
for ( initialization-expression;
testing-expression; counting-expression;)
{
statements;
}
The three expressions in the parentheses following the keyword for control how the for loop works.
-- The
initialization-expression
is executed before the loop begins. If we haven't initialize a
counter variable before the loop, we
can do so here.
-- The
testing-expression
is evaluated each time the loop is executed to determine whether the loop
should continue. In other word, if
this condition is still true, continue looping otherwise exit the loop.
-- The
counting-expression
is evaluated each time the loop executes. Its job is to increment or decrement
the counter variable.
Example) We will use a loop to print out the numbers from 0 to 5.
public class Count
{
public static void main(String[] args)
{
for(int i = 0; i < 6; i++)
{
System.out.println(i);
}
}
}
ClickHere to download Count.java
Now, look at the example above, notice we
have i < 6, the reason is because once i = 6 or higher
the loop will end, hence the highest we would be able to print out is 5.
Sometimes we want to get out of a
loop before executing some statements, thus we have a keyword "break,"
it can force out a loop.
Example) This program will only output 0
public class Count
{
public static void main(String[] args)
{
for(int i = 0; i < 6; i++)
{
System.out.println(i);
break;
}
}
}
Notice, here the statement will only execute once because once we reach to break, the loop will end.
Example) This program prints out even and odd numbers
public class SumEven
{
public static void main(String[] args)
{
System.out.print("Even " + "odd\n");
for(int i = 0; i < 11; i++)
{
if(i%2==0)
{
System.out.print(i + "\n");
}
else
{
System.out.print("\t " + i + "\n");
}
}
}
}
ClickHere to download SumEven.java
.
Now, lets look at one of the most basic loop " while loop." The basic format for
a while loop is as follow.
while (expression)
statement;
The while statement begins by evaluating the
expression. If the expression is true,
the statement is executed.
Then the expression is evaluated again, and the whole process repeats until the
expression is false.
Example) Using a while loop to print out numbers from 1 to 5
public class WhileCount
{
public static void main(String[] args)
{
int number = 1;
while(number < 6 )
{
System.out.println(number);
number++;
}
}
}
ClickHere to download WhileCount.java
Now, lets look at another loop, the
do-while loop
( sometimes called a do loop
) is very similar to a while loop.
In a do-while loop, we execute the statement first than check the condition
expression after. Here is the basic
form for a do while loop.
do
{
statement;
}while(expression);
Example) Using a do-while loop to print out numbers from 1 to 5.
public class DoWhileCount
{
public static void main(String[] args)
{
int number = 1;
do
{
System.out.println(number);
number++;
}while(number < 6);
}
}
ClickHere to download DoWhileCount.java
Now lets wrap up everything together and see some bigger examples.
/* This is a basic program that uses a for loop
It asks the user for a series of grade
Then it calculates the average of the grade
Hence, it determines the letter grade and print it out
*
*/
import java.util.Scanner;
public class Forloop
{
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
double grade;
int num;
double sum = 0.0, ave = 0.0;
// Here will deteremine how many times we will loop
System.out.print("How many grades are
you planning to input\n");
num = key.nextInt();
/* Creates a for loop with "num" of times, starting at 0
The loop will exit once i is greater than or equal to num
*
*/
for (int i=0; i<num; i++)
{
// Asks the user for their grade
System.out.print("Enter your first grade: \n");
grade =
key.nextDouble();
sum +=grade;
// Calculates the sum of the grade
}
ave = sum / num; // Cacluate the
average
// We use a else-if statement to determine the letter grade
if(ave>=90)
{
System.out.print("You recieve an A\n");
}
else if(ave>=80)
{
System.out.print("You recieve a B\n");
}
else if(ave>=70)
{
System.out.print("You recieve a C\n");
}
else if(ave>=60)
{
System.out.print("You recieve a D\n");
}
else
{
System.out.print("You recieve a F\n");
}
}
}
ClickHere to download Forloop.java
ClickHere to download Whileloop.java
ClickHere to download Dowhileloop.java