Transcript chapter03
Part I: Chapter 03
Control Statements
Objectives
• To understand the concept of program control.
• To use selection statements to control the
execution of programs.
• To use loop statements to control the repetition of
statements.
• To understand and use the keywords break and
continue.
2
Types of Control Statement
• Sequential Statements
• Selection Statements
– if
– switch… case
• Loop Statements
– do .. While
– while .. Do
– for
3
Selection Statements
• Simple if statements
if (booleanExpression)
{
statement(s);
}
Boolean
Expression
False
True
Statement(s)
Next Statement
4
Selection Statements
• if … else statements
if (booleanExpression)
{
//for the true case
statement(s);
}
else
{
//for the false case
statement(s);
}
Boolean
Expression
False
True
Statement(s)
for true case
Statement(s)
for false case
Next Statement
5
Selection Statements
Pseudocode statement
If student's grade is greater
than or equal to 60
Print "Passed"
Else
Print "Failed"
Java statement
if ( studentGrade >= 60 )
System.out.println (
"Passed" );
else
System.out.println (
"Failed" );
6
Selection Statements
• Nested if Statements
if (booleanExpression1) {
if (booleanExpression2) {
statement(s);
}
}
else {
statement(s);
}
7
Selection Statements
• Nested if Statements
if (booleanExpression1) {
statement(s);
}
else {
if (booleanExpression2) {
statement(s);
}
else {
statement(s);
}
}
8
Quiz!
• What is the output of the following program.
int i
int j
int k
if (i
if
= 1;
= 2;
= 3;
> j)
(i > k)
System.out.println(“A”);
else
System.out.println(“B”);
CS216 / SE211
9
Quiz!
• What is the output of the following
program.
int i = 1;
int j = 2;
int k = 3;
if (i > j);
System.out.println(“A”);
else
System.out.println(“B”);
10
Selection Statements
• Switch Statements
switch (x) {
case valueOne:
...
// x is valueOne
break;
case valueTwo:
...
// x is valueTwo
break;
default:
...
// other value of x
}
•
The value of x must yield a value of char, byte, short, or
int type and must always be enclosed in parentheses.
11
Selection Statements
• Switch Statements (Examples)
switch (numOfYears) {
case 7: annualInterestRate = 7.25;
case 15: annualInterestRate = 8.50;
case 30: annualInterestRate = 9.0;
default: System.out.println(“Wrong
number ofyears”);
}
12
Selection Statements
• Conditional Expressions
if (x > 0)
y = 1;
else
y = -1;
The above code is equivalent to
y = (x > 0) ? 1 : -1;
13
Quiz!
• Write the following expression in terms of
if..else statement.
1) max = (num1 > num2) ? num1 : num2;
2) System.out.println(
(num%2 == 0) ? “num is even” :
“num is odd”
);
14
Loop Statements
•
The for loop
for (part1; part2; part3) {
...
...
}
•
•
•
part1 = an index initialization
part2 = terminating condition
part3 = changing value of the index
15
Loop Statements
• The for loop (Example)
int sum = 0;
for (int n = 1; n <= 100; n++)
sum += n;
16
Loop Statements
• The while loop
while (condition) {
...
...
}
• Check the condition, if the condition is true then
the statements in the while loop block are
processed.
17
Loop Statements
• The while loop (Example)
int product = 2;
while ( product <= 1000 )
product = product * 2;
18
Loop Statements
•
The do-while loop
do {
...
...
} while (condition);
•
•
The statements in the do..while loop block are
done at least one time.
The loop will end when the condition is false.
19
Loop Statements
• The do-while loop (Example)
int counter = 1;
do {
System.out.print ( "Line number" );
System.out.println ( counter );
++counter;
}
while ( counter <= 10 );
20
Quiz!
• Identify the different among for, while,
and do..while loop. Give a suitable
case for each loop.
Loop Statements: Example II
import javax.swing.JOptionPane;
public class Average {
public static void main ( String args[] )
int sum, n, num, avg;
String value;
// initialise sum to zero
sum = 0;
{
for ( n=1; n<=10; n++) {
// get a number from user
value = JOptionPane.showInputDialog
("Enter number: ");
// convert the number (value) from a String to an integer
}
num = Integer.parseInt
// add num to sum
sum = sum + num;
// end of for loop
(value);
22
Loop Statements: Example II
// calculate the average
avg = sum / 10;
// display the average of all 10 numbers
JOptionPane.showMessageDialog (null, "Average
number is "+avg, "Average",
JOptionPane.INFORMATION_MESSAGE );
System.exit(0);
}
}
// terminate the program
// end of method main
// end of class Average
23
Loop Statements: Example III
public class PrintStar {
public static void main ( String args[] )
{
for (int row=1; row <=5; row++)
{
System.out.println();
for (int col=1; col <= row; col++)
{
System.out.print("*");
} // end of for 'col'
}
// end of for 'row'
} // end of method main
} // end of class PrintStar
24
Loop Statements: Example IV
import java.awt.Graphics;
import javax.swing.JApplet;
public class CircleLoop extends JApplet {
public void paint ( Graphics g ) {
int counter = 1;
do {
g.drawOval(110-counter*10,110–counter*10,
counter * 20, counter * 20);
++counter;
} while (counter <= 10 );
}
}
25
break and continue
• break immediately ends the innermost
loop that contains it.
• continue only ends the current iteration.
Program control goes to the end of the
loop body.
26
break and continue: Example
public class TestBreak
{
public static void main(String args[])
{
int sum = 0, item = 0;
while (item < 5) {
item++;
sum += item;
if (sum >= 6) break;
}
System.out.println(“The sum is “ + sum);
}
}
27
break and continue: Example
public class TestContinue
{
public static void main(String args[])
{
int sum = 0, item = 0;
while (item < 5) {
item++;
if (item == 2) continue;
sum += item;
}
System.out.println(“The sum is “ + sum);
}
}
28
Quiz!
• Write a Java program to get a value of radius of a
circle and validate it before its area calculation
public class RadiusCalculation {
public static void main(String args[]) {
– Get a value of radius
– If radius >= 0
» Compute the area using the following formula: area = r2
» Display area
– Else
» Write a message to user to inform about invalid input and try
to get a value again
}
}
29
Quiz!
• Show the output, if any, of the following code.
x = 2;
y = 3;
if ( x > 2 )
if ( y > 2 ) {
int z = x + y;
System.out.println(“z is “+ z);
}
else
System.out.println(“x is “+ x);
30
Quiz!
• Show the output of the following program.
public class Test {
public static void main (String args[]) {
int i = 0;
while ( i < 5) {
for (int j = i; j > 1; j--);
System.out.print(j + “ “);
System.out.println(“****”);
i++;
}
}
}
31
End of Chapter 03
Control Statements