You are on page 1of 33

Loops

• Sometimes we need to execute a block of code


several number of times.
• In general, statements are executed sequentially:
The first statement in a function is executed first,
followed by the second, and so on.
• Programming languages provide various control
structures that allow for more complicated
execution paths.
• A loop statement allows us to execute a statement
or group of statements multiple times.
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Outline
The While loop
The do –while loop
The for Loop
Conditional Operator
Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The while Statement
• A while statement has the following syntax:
while ( condition )
{
statement;

}
• If the condition is true, the statement is executed

• Then the condition is evaluated again, and if it is still true,


the statement is executed again
• The statement is executed repeatedly until the condition
becomes false
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Logic of a while Loop

condition
evaluated

false
true

statement

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


An example of a while statement:

int count = 1;
while (count <= 5)
{
System.out.println (count);
count++;
}

•If the condition of a while loop is false initially,


the statement is never executed
•Therefore, the body of a while loop will execute
zero or more times
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Sentinel Values
• A sentinel value is a special input value that
represents the end of input
• Sentinel values are often used:
– When you don’t know how many items are in a list, use a
‘special’ character or value to signal no more items.
– For numeric input of positive numbers, it is common to use
the value -1:
salary == in.nextDouble();
salary in.nextDouble();
while (salary
while (salary !=
!= -1)
-1)
{{
sum == sum
sum sum ++ salary;
salary;
count++;
count++;
salary == in.nextDouble();
salary in.nextDouble();
}}
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
SentinelDemo.java (1)

Outside the while loop, declare and


initialize variables to use

Since salary is initialized to 0, the while


loop statements will be executed

Input new salary and


compare to sentinel

Update running sum and


count to average later

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and


Management University
SentinelDemo.java (2)

Prevent divide by 0

Calculate and output the


average salary using sum
and count variables

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and


Management University
Outline
The While loop
The do –while loop
The for Loop
Conditional Operator
Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The do-while loop
• A do statement has the following syntax:
do
{
statement-list;
}
while (condition);

• The statement-list is executed once initially,


and then the condition is evaluated
• The statement is executed repeatedly until the
condition becomes false
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Logic of a do Loop
statement

true

condition
evaluated

false

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Do while example

int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Comparing
The while Loop
while and do
The do Loop

statement
condition
evaluated
true

condition
true false
evaluated

statement
false

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Outline
The While loop
The do –while loop
The for Loop
Conditional Operator
Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The for- loop
• A for statement has the following syntax:
The initialization The statement is
is executed once executed until the
before the loop begins condition becomes false

for ( initialization ; condition ; increment )


statement;

The increment portion is executed at


the end of each iteration

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Logic of a for loop

initialization

condition
evaluated

true false

statement

increment

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The for Statement
• A for loop is functionally equivalent to the
following while loop structure:

initialization;
while ( condition )
{
statement;
increment;
}

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The for Statement
• An example of a for loop:
for (int count=1; count <= 5; count++)
System.out.println (count);

• The initialization section can be used to declare a


variable
• Like a while loop, the condition of a for loop is
tested prior to executing the loop body
• Therefore, the body of a for loop will execute
zero or more times
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Nested for-loop

//********************************************************************
// Stars.java //
// Demonstrates the use of nested for loops.
//********************************************************************

public class Stars


{
//-----------------------------------------------------------------
// Prints a triangle shape using asterisk (star) characters.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++)


{
for (int star = 1; star <= row; star++)
System.out.print ("*");

System.out.println();
}
}
}
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
//********************************************************************
// Stars.java Author: Lewis/Loftus
//
// Demonstrates the use of nested for loops.
//********************************************************************

public class Stars


{ Output
//-----------------------------------------------------------------
// Prints a triangle shape using asterisk (star) *characters.
//-----------------------------------------------------------------
**
public static void main (String[] args) ***
{
****
final int MAX_ROWS = 10;
*****
for (int row = 1; row <= MAX_ROWS; row++) ******
{ *******
for (int star = 1; star <= row; star++) ********
System.out.print ("*"); *********
**********
System.out.println();
}
}
}

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Outline
The While loop
The do –while loop
The for Loop
Conditional Operator
Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


The Conditional Operator
• The conditional operator evaluates to one of two
expressions based on a boolean condition
• Its syntax is:
condition ? expression1 : expression2

• If the condition is true, expression1 is


evaluated; if it is false, expression2 is
evaluated
• The value of the entire conditional operator is the
value of the selected expression
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
The Conditional Operator
• The conditional operator is similar to an if-else
statement, except that it is an expression that returns
a value
• For example:
larger = ((num1 > num2) ? num1 : num2);

• If num1 is greater than num2, then num1 is assigned


to larger; otherwise, num2 is assigned to larger
• The conditional operator is ternary because it requires
three operands
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
The Conditional Operator
• Another example:
System.out.println ("Your change is " + count +
((count == 1) ? "Dime" : "Dimes"));

• If count equals 1, the "Dime" is printed


• If count is anything other than 1, then "Dimes"
is printed

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Quick Check
Express the following logic in a succinct manner
using the conditional operator.
if (val <= 10)
System.out.println("It is not greater than 10.");
else
System.out.println("It is greater than 10.");

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Quick Check
Express the following logic in a succinct manner
using the conditional operator.

if (val <= 10)


System.out.println("It is not greater than 10.");
else
System.out.println("It is greater than 10.");

System.out.println("It is" +
((val <= 10) ? " not" : "") +
" greater than 10.");

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Outline
The While loop
The do –while loop
The for Loop
Conditional Operator
Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Dialog Boxes
• A dialog box is a window that appears on top of any
currently active window
• It may be used to:
– convey information
– confirm an action
– allow the user to enter data
– pick a color
– choose a file

• A dialog box usually has a specific, solitary purpose,


and the user interaction with it is brief
Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University
Dialog Boxes
• The JOptionPane class provides methods that
simplify the creation of some types of dialog
boxes

• See EvenOdd.java

• Specialized dialog boxes for choosing colors and


files are covered in Chapter 9

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


/********************************************************************
// EvenOdd.java //
// Demonstrates the use of the JOptionPane class.
//********************************************************************

import javax.swing.JOptionPane;

public class EvenOdd


{
//-----------------------------------------------------------------
// Determines if the value input by the user is even or odd.
// Uses multiple dialog boxes for user interaction.
//-----------------------------------------------------------------
public static void main (String[] args)
{
String numStr, result;
int num, again;

continue

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


continue

do
{
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
num = Integer.parseInt(numStr);

result = "That number is " + ((num%2 == 0) ? "even" : "odd");

JOptionPane.showMessageDialog (null, result);


again = JOptionPane.showConfirmDialog (null, "Do Another?");
}
while (again == JOptionPane.YES_OPTION);
}
}

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


continue

do
{
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
num = Integer.parseInt(numStr);

result = "That number is " + ((num%2 == 0) ? "even" : "odd");

JOptionPane.showMessageDialog (null, result);


again = JOptionPane.showConfirmDialog (null, "Do Another?");
}
while (again == JOptionPane.YES_OPTION);
}
}

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University


Summary
• Lecture focused on:
 The While loop
 The do –while loop
 The for Loop
 Conditional Operator
 Dialog boxes

Copyright@ 2016 Allan Ninyesiga, Uganda Technology and Management University

You might also like