0% found this document useful (0 votes)
47 views74 pages

Chapter 2 Par 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views74 pages

Chapter 2 Par 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 74

Chapter 2

Control
Statements
Cont’d …
• Now we will examine programming statements
that allow us to:
 make decisions
 repeat processing steps in a loop
Java’s program control statements can be put into the
following categories: selection, iteration,and jump.
Selection statements allow your program to choose
different paths of execution based upon the outcome of
an expression or the state of a variable
.Iteration statements enable program execution to repeat
one or more statements (that is, iteration statements
form loops).
Jumps tatements allow your program to execute in a
nonlinear fashion
Flow of Control
• Unless specified otherwise, the order of statement
execution through a method is linear: one
statement after another in sequence

• Some programming statements allow us to:


 decide whether or not to execute a particular statement
 execute a statement over and over, repetitively

• These decisions are based on boolean expressions


(or conditions) that evaluate to true or false

• The order of statement execution is called the flow


of control
Conditional Statements
• A conditional statement lets us choose which
statement will be executed next

• Therefore they are sometimes called selection


statements

• Conditional statements give us the power to


make basic decisions

• The Java conditional statements are the:


 if statement
 if-else statement
 switch statement
The if Statement
• The if statement has the following syntax:

The condition must be a


boolean expression. It must
if is a Java evaluate to either true or false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.
Logic of an if statement

condition
evaluated

true
false

statement
Boolean Expressions
• A condition often uses one of Java's equality
operators or relational operators, which all return
boolean results:

higher == equal to
precedence != not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

• Note the difference between the equality operator


(==) and the assignment operator (=)
The if Statement
• An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
System.out.println ("The sum is " + sum);

• First the condition is evaluated -- the value of sum


is either greater than the value of MAX, or it is not

• If the condition is true, the assignment statement


is executed -- if it isn’t, it is skipped.

• Either way, the call to println is executed next


The if Statement
• What do the following statements do?
if (top >= MAXIMUM)
top = 0;
Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUM

if (total != stock + warehouse)


inventoryError = true;

Sets a flag to true if the value of total is not equal to


the sum of stock and warehouse
 The precedence of the arithmetic operators is
higher than the precedence of the equality and
relational operators
Logical Operators
• Boolean expressions can also use the following
logical operators:
! Logical NOT
&& Logical AND
|| Logical OR

• They all take boolean operands and produce


boolean results
• Logical NOT is a unary operator (it operates on
one operand)
• Logical AND and logical OR are binary operators
(each operates on two operands)
Logical NOT
• The logical NOT operation is also called logical
negation or logical complement
• If some boolean condition a is true, then !a is
false; if a is false, then !a is true
• Logical expressions can be shown using a truth
table
a !a
true false
false true

Consider a ‘condition’ something like (age > 25)


It is either true or false (boolean result)
Logical AND and Logical OR
• The logical AND expression a && b

is true if both a and b are true, and false otherwise

• The logical OR expression a || b

is true if a or b or both are true, and false


otherwise

Examples: if ( a> 14 && b == 6)


a++;
if (a > 14 || b == 6)
b--;
Logical Operators
• Expressions that use logical operators can form
complex conditions

if (total < MAX+5 && !found)


System.out.println ("Processing…");

• All logical operators have lower precedence than


the relational operators, which have lower
precedence than arithmetic operators.

• Logical NOT has higher precedence than logical


AND and logical OR
Logical Operators
• A truth table shows all possible true-false
combinations of the terms

• Since && and || each have two operands, there


are four possible combinations of conditions a
and b

a b a && b a || b
true true true true
true false false true
false true false true
false false false false
Boolean Expressions
• Specific expressions can be evaluated using truth
tables

total < MAX found !found total < MAX && !found
false false true false
false true false false
true false true true
true true false false
The if-else Statement
• An else clause can be added to an if statement to
make an if-else statement

if ( condition )
statement1;
else
statement2;

• If the condition is true, statement1 is executed;


if the condition is false, statement2 is executed

• One or the other will be executed, but not both


Logic of an if-else statement

condition
evaluated

true false

statement1 statement2
Switch Statements
• The switch statement is Java’s multiway branch
statement. As such, it often provides a better
alternative than a large series of if-else-if
statements. Here is the general form of a switch
statement.
switch (expression) {

casevalue1:

break;

casevalue2:

// statement sequence

break;

casevalueN:

// statement sequence

break;

default:

// default statement sequence

}
…Switch Statements
• The expression must be of type byte,short,int, or
char; each of the values specified in the case
statements must be of a type compatible with the
expression. Each case value must be a unique literal
(that is, it must be a constant, not a variable).
Duplicate case values are not allowed.

• The switch statement works like this: The value of


the expression is compared with each of the literal
values in the case statements. If a match is found,
the code sequence following that case statement is
executed. If none of the constants matches the
value of the expression, then the default statement
is executed. However, the default statement is
optional. If no case matches and no default is
present, then no further action is taken.
• The break statement is used inside the switch to terminate a
statement sequence. When a break statement is
encountered, execution branches to the first line of code that
follows the entire switch statement.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;

… case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
Repetition Statements
• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
 the while loop
 the do loop
 the for loop

• The programmer should choose the right kind of


loop for the situation
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
Logic of a while Loop

condition
evaluated

true false

statement
The while Statement
• 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
The while Repetition Structure
• Flowchart of while loop
int product
int product == 2;
2;
while (( product
while product <=<= 1000
1000 ))
product == 22 ** product;
product product;
int product = 2 System.out.println(product);
System.out.println(product);

true
product <= 1000 product = 2 * product

false
Parts of a while loop
int x = 1;
while (x < 10) {
System.out.println(x);
x++;
}
• Label the following loop
int product = 2;
while ( product <= 1000 )
product = 2 * product;
Another loop example
• Label the parts of the loop
int x = 1;
int y = 2;
while (x < 10)
{
System.out.println(x + “ “ + y);
y *= 2;
x++;
}
while loop format
• Sum the numbers from 1 to 100
Average.java
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();

while (value != 0) // sentinel value of 0 to


// terminate loop
{
count++;

sum += value;
System.out.println ("The sum so far is " + sum);

System.out.print ("Enter an integer (0 to quit): ");


value = scan.nextInt();
}
Average.java
System.out.println ();

if (count == 0)
System.out.println ("No values were entered.");
else
{
average = (double)sum / count;

System.out.println ("The average is " + average);


}
}
}
Infinite Loops
• The body of a while loop eventually must make
the condition false

• If not, it is called an infinite loop, which will


execute until the user interrupts the program

• This is a common logical error

• You should always double check the logic of a


program to ensure that your loops will terminate
normally
Infinite Loops
• An example of an infinite loop:

int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}

• This loop will continue executing until interrupted


(Control-C) or until an underflow error occurs
Nested Loops
• How many times will the string "Here" be printed?

count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
System.out.println ("Here");
count2++;
}
count1++;
}
The do Statement
• A do statement has the following syntax:

do
{
statement;
}
while ( condition )

• The statement is executed once initially, and then


the condition is evaluated

• The statement is executed repeatedly until the


condition becomes false
Logic of a do Loop

statement

true

condition
evaluated

false
The do Statement
• An example of a do loop:

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

• The body of a do loop executes at least once


ReverseNumber.java
System.out.print ("Enter a positive integer: ");
number = scan.nextInt();

do
{
lastDigit = number % 10;
reverse = (reverse * 10) + lastDigit;
number = number / 10;
}
while (number > 0);

System.out.println ("That number reversed is " +


reverse);

Output Enter a positive integer: 13667


That number reversed is 76631
Comparing while and do
The while Loop The do Loop

statement
condition
evaluated
true

condition
true false
evaluated

statement
false
The for Statement
• 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
Logic of a for loop

initialization

condition
evaluated

true false

statement

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

initialization;
while ( condition )
{
statement;
increment;
}
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
The for Statement
• The increment section can perform any calculation

for (int num=100; num > 0; num -= 5)


System.out.println (num);

• A for loop is well suited for executing statements


a specific number of times that can be calculated
or determined in advance
Stars.java
//---------------------------------------------------
// 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();
}
}
The for Statement
• Each expression in the header of a for loop is
optional

• If the initialization is left out, no initialization is


performed

• If the condition is left out, it is always considered


to be true, and therefore creates an infinite loop

• If the increment is left out, no increment operation


is performed
for loop Exercises
• How many times is the loop body
repeated?
 for (int x = 3; x <= 15; x += 3)
System.out.println(x);
 for (int x = 1; x <= 5; x += 7)
System.out.println(x);
 for (int x = 12; x >= 2; x -= 3)
System.out.println(x);
• Write the for statement that print the
following sequences of values.
 1, 2, 3, 4, 5, 6, 7
 3, 8, 13, 18, 23
 20, 14, 8, 2, -4, -10
 19, 27, 35, 43, 51
Jump Statements
• Java supports three jump statements :break, continue, and
return. These statements
• transfer control to another part of your program
• Using break to Exit a Loop
• Continue statement causes control to be transferred
directly to the conditional expression that controls
the loop
• The return statement is used to explicitly return
• from a method
Break Example
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output 0---9
Continue Example(odd numbers)
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if (i%2 == 0) continue;
System.out.print(i + " ");
}
}
}
Output 1,3,5,7,9
Exercise
• How many times is the following loop body repeated? What
is printed during each repetition of the loop body and after
exit?
x = 3;
for (int count = 0; count < 3; count++)
{
x = x * x;
System.out.println(x);
}
System.out.println(x);
Exercise
• What mathematical result does the following
fragment compute and display?
System.out.print("Enter x: ");
int x = scan.nextInt();
System.out.print("Enter y: ");
int yFirst = scan.nextInt();
int product = 1;
for (int y = yFirst; y > 0; y--)
product *= x;
System.out.println(“result = “ + product);
Nested loops. What do these print?
• for (int i = 1; i < 4; i++)
for (int j = 1; j < i; j++)
System.out.println(i + “ “ + j);
• for (int i = 0; i < 4; i++)
for (int j = 1; j < i; j++)
System.out.println(i + “ “ + j);
• for (int i = 1; i < 4; i++)
for (int j = 1; j < i; j++)
System.out.println(i + “ “ + j);
System.out.println(“******”);
• int T = 0;
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 2*i; j += 2)
T += j * i;
System.out.println(“T = “ + T);
}
Using a loop to find if a number is
prime
• Write a number is Prime numbers or not; PN are
only divisible by 1 and themselves
• Write a number that displays palindrome number
Array
Declaring an Array Variable
• Do not have to create an array while declaring
array variable
 <type> [] variable_name;
 int [] prime;
 int prime[];
• Both syntaxes are equivalent
• No memory allocation at this point
Defining an Array
• Define an array as follows:
 variable_name=new <type>[N];
 primes=new int[10];
• Declaring and defining in the same statement:
 int[] primes=new int[10];
• In JAVA, int is of 4 bytes, total space=4*10=40
bytes
Graphical Representation

Index
prime

0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2

value
Default Initialization
• When array is created, array elements are
initialized
 Numeric values (int, double, etc.) to 0
 Boolean values to false
 Char values to ‘\u0000’ (unicode for blank character)
 Class types to null
Accessing Array Elements
• Index of an array is defined as
 Positive int, byte or short values
 Expression that results into these types
• Any other types used for index will give
error
 long, double, etc.
 Incase Expression results in long, then type
cast to int
• Indexing starts from 0 and ends at N-1
primes[2]=0;
int k = primes[2];

Validating Indexes
• JAVA checks whether the index values are valid at
runtime
 If index is negative or greater than the size of the array
then an IndexOutOfBoundException will be thrown
 Program will normally be terminated unless handled in
the try {} catch {}
Initializing Arrays
• Initialize and specify size of array while
declaring an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
• You can initialize array with an existing
array
int[] even={2,4,6,8,10};
int[] value=even;
 One array but two array variables!
 Both array variables refer to the same array
 Array can be accessed through either variable
name
Graphical Representation

even

0 1 2 3 4
2 4 6 8 10

value
Demonstration
long[] primes = new long[20];
primes[0] = 2;
primes[1] = 3;
long[] primes2=primes;
System.out.println(primes2[0]);
primes2[0]=5;
System.out.println(primes[0]);
Output
2
5
Array Length
• Refer to array length using length
 A data member of array object
 array_variable_name.length
 for(int k=0; k<primes.length;k++)
….
• Sample Code:
long[] primes = new long[20];
System.out.println(primes.length);
• Output: 20
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum
for ( int index=0; index < array.length; index++ )
if ( array[ index ] < min )
min = array[ index ] ;
System.out.println("The minimum of this array is: " + min
);
}
}

*Program taken from: http://chortle.ccsu.edu/CS151/Notes/chap47/ch47_10.html


Arrays of Arrays
• Two-Dimensional arrays
 float[][] temperature=new float[10][365];
 10 arrays each having 365 elements
 First index: specifies array (row)
 Second Index: specifies element in that array (column)
 In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
Graphical Representation

Sample[0] 0 1 2 3 4 5 6 7 8 9

Sample[1] 0 1 2 3 4 5 6 7 8 9

Sample[2] 0 1 2 3 4 5 6 7 8 9
Initializing Array of Arrays
int[][] array2D = { {99, 42, 74, 83, 100},
{90, 91, 72, 88, 95}, {88, 61, 74, 89,
96}, {61, 89, 82, 98, 93}, {93, 73, 75,
78, 99}, {50, 65, 92, 87, 94}, {43, 98,
78, 56, 99} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying Length
• All arrays do not have to be of the same length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
• Not required to define all arrays
Initializing Varying Size Arrays
int[][] uneven = { { 1, 9, 4 }, { 0, 2},
{ 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];
primes[2] = new long[30];
System.out.println(primes.length); //Number of arrays
System.out.println(primes[2].length);//Number of elements in the
second array

OUTPUT:
20
30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2,
3, 4 } };
// print out the array
for ( int row=0; row < uneven.length; row++ )
//changes row
{
System.out.print("Row " + row + ": ");
for ( int col=0; col < uneven[row].length;
col++ ) //changes column
System.out.print( uneven[row][col] + "
"); System.out.println();
}
}
}
Output
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy