[go: up one dir, main page]

0% found this document useful (0 votes)
9 views48 pages

Chapter 3 Descion & Repeation Statements & Arrays 1

Chapter 3 discusses control structures in Java, focusing on decision statements and loops. It explains how decision statements like if and switch control the flow of a program, while loops such as while and for allow repeated execution of code blocks. Additionally, the chapter covers arrays, their declaration, initialization, and how to access and manipulate their elements.

Uploaded by

asnake ketema
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)
9 views48 pages

Chapter 3 Descion & Repeation Statements & Arrays 1

Chapter 3 discusses control structures in Java, focusing on decision statements and loops. It explains how decision statements like if and switch control the flow of a program, while loops such as while and for allow repeated execution of code blocks. Additionally, the chapter covers arrays, their declaration, initialization, and how to access and manipulate their elements.

Uploaded by

asnake ketema
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/ 48

Chapter 3:

Decision & Repetition


Statements and Array

AU/Computer Sc. Dept./OOP lecture


slides 1
Program Flow
 Java will execute the a more sophisticated program
statements in your code in
statement
a specific sequence, or
"flow". statement
 The "flow" of the program
and can be described
through a "flow diagram":
statement statement
a simple program

statement
statement
statement

statement

statement statement
AU/Computer Sc. Dept./OOP lecture
slides 2
What are Control
Structures?
Control structures alter the flow of the
program, the sequence of statements
that are executed in a program.

They act as "direction signals" to


control the path a program takes.

Two types of control structures in Java:


◦ decision statements
◦ loops

AU/Computer Sc. Dept./OOP lecture


slides 3
Decision Statements
Adecision statement allows
the code to execute a
statement or block of
statements conditionally.

Two types of decisions


statements in Java:
◦ if statements
◦ switch statements
AU/Computer Sc. Dept./OOP lecture
slides 4
If Statement
if (expression) {
statement;
}
rest_of_program;

 expression must evaluate to a boolean


value, either true or false
 Ifexpression is true, statement is
executed and then rest_of_program
 Ifexpression is false, statement is not
executed and the program continues at
rest_of_program
AU/Computer Sc. Dept./OOP lecture
slides 5
If Statement Flow Diagram
The if decision statement
executes
a statement if an expression is
no
true Is expression
true?

if (expression) { yes
statement1;
} execute
statement
rest_of_program

execute
rest_of_program
AU/Computer Sc. Dept./OOP lecture
slides 6
If-Else Statement
if (expression) {
statement1;
}
else{
statement2;
}
next_statement;

Again, expression must produce a


boolean value
If expression
is true, statement1 is
executed and then next_statement is
executed.
If expression
is false, statement2 is
executed and then next_statement is
executed. AU/Computer Sc. Dept./OOP lecture
slides 7
If-Else Flow Diagram
The if-else decision
statement executes a
statement if an is
yes no
“expression”
expression is true and a true?
different statement if it is
not true.
execute execute
if (expression){
statement1 statement2
statement1;
} else {
statement2;
} execute
rest_of_program rest_of_program
AU/Computer Sc. Dept./OOP lecture
slides 8
Chained If-Else
Statements
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");

AU/Computer Sc. Dept./OOP lecture


slides 9
Switch Statements
 The switch statement enables you to test several
cases generated by a given expression.

 For example:
switch (expression) {
case value1:
statement1;
case value2:
statement2;
default:
default_statement;
}
Every statement after the true case is executed

 The expression must evaluate to a char, byte,


short or int, but not long, float, or double.
AU/Computer Sc. Dept./OOP lecture
slides 10
expression y
equals Do value1 thing
value1?
switch (expression){
case value1:
// Do value1 thing n
case value2:
// Do value2 thing
expression y
equals Do value2 thing
...
default: value2?
// Do default action
}
// Continue the program n

Do default action

Continue the
program

AU/Computer Sc. Dept./OOP lecture


slides 11
Break Statements in Switch
Statements
The break statement tells the computer to
exit the switch statement
For example:
switch (expression) {
case value1:
statement1;
break;
case value2:
statement2;
break;
default:
default_statement;
break;
}
AU/Computer Sc. Dept./OOP lecture
slides 12
switch (expression){ expression y
case value1: equals Do value1 thing break
// Do value1 thing value1?
break;

case value2: n
// Do value2 thing
break;
expression y
... equals Do value2 thing break
default: value2?
// Do default action
break;
} n
// Continue the program

do default action

Continue the
break
program

AU/Computer Sc. Dept./OOP lecture


slides 13
Remember the Chained If-Else
...
if (grade == 'A')
System.out.println("You got an A.");
else if (grade == 'B')
System.out.println("You got a B.");
else if (grade == 'C')
System.out.println("You got a C.");
else
System.out.println("You got an F.");

AU/Computer Sc. Dept./OOP lecture


slides 14
This is how it is accomplished with a
switch:
switch (grade) {
case 'A':
System.out.println("You got an A.");
break;
case 'B':
System.out.println("You got a B.");
break;
case 'C':
System.out.println("You got a C.");
break;
default:
System.out.println("You got an F.");
}
if-elsechains can be sometimes be
rewritten as a “switch” statement.
switches are usually simpler and faster
AU/Computer Sc. Dept./OOP lecture
slides 15
Loops
 A loop allows you to execute a
statement or block of statements
repeatedly.

 Three types of loops in Java:


1. while loops
2. for loops
3. do-while loops (not discussed in this
course)

AU/Computer Sc. Dept./OOP lecture


slides 16
The while Loop
while (expression){
statement
}

 Thiswhile loop executes as long as the given


logical expression between parentheses is true.
When expression is false, execution continues
with the statement following the loop block.

 Theexpression is tested at the beginning of the


loop, so if it is initially false, the loop will not
be executed at all.
AU/Computer Sc. Dept./OOP lecture
slides 17
For example:

int sum = 0;
int i = 1;

while (i <= 10){


sum += i;
i++;
}

What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

AU/Computer Sc. Dept./OOP lecture


slides 18
The for Loop
for (init_expr; loop_condition; increment_expr)
{
statement;
}
The control of the for loop appear in parentheses and is
made up of three parts:

1. The first part, the init_expression,sets the initial


conditions for the loop and is executed before the loop
starts.

2. Loop executes so long as the loop_condition is true


and exits otherwise.

3. The third part of the control information, the


increment_expr, is usually used to increment the loop
counter. This is executed at the end of each loop
iteration. AU/Computer Sc. Dept./OOP lecture
slides 19
For example:

int sum = 0;

for (int i = 1; i <= 10; i++) {


sum += i;
}

What is the value of sum?

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

AU/Computer Sc. Dept./OOP lecture


slides 20
Example 3:

for(int div = 0; div < 1000; div++){


if(div % 2 == 0) {
System.out.println("even: " +
div);
} else {
System.out.println("odd: " + div);
}
}

What will this for loop do?

prints out each integer from 0 to 999,


correctly labeling them even or odd
AU/Computer Sc. Dept./OOP lecture
slides 21
Ifthere is more than one variable to set up
or increment they are separated by a
comma.

for(i=0, j=0; i*j < 100; i++, j+=2) {


System.out.println(i * j);
}

You do not have to fill all three control


expressions but you must still have two
semicolons.

int n = 0;
for(; n <= 100;) {
System.out.println(++n);
}
AU/Computer Sc. Dept./OOP lecture
slides 22
The for loop

Initialize count
The while loop

n n
Test condition Test condition
is true? is true?

y
y
Execute loop
statement(?) Execute loop
statement(s)

Increment
Next statement count

New statement
AU/Computer Sc. Dept./OOP lecture
slides 23
The continue Statement
The continue statement causes the
program to jump to the next iteration of
the loop.

/**
* prints out "5689"
*/
for(int m = 5; m < 10; m++) {
if(m == 7) {
continue;
}
System.out.print(m);
} AU/Computer Sc. Dept./OOP lecture
slides 24
Another continue example:

int sum = 0;
for(int i = 1; i <= 10; i++){
if(i % 3 == 0) {
continue;
}
sum += i;
}

What is the value of sum?


1 + 2 + 4 + 5 + 7 + 8 + 10 = 37

AU/Computer Sc. Dept./OOP lecture


slides 25
The break Statement
We have seen the use of the break
statement in the switch statement.
You can also use the break statement
to exit the loop entirely.
// prints out numbers unless
// num is ever exactly 400
while (num > 6) {
if(num == 400) {
break;
}
System.out.println(num);
num -= 8;
}
AU/Computer Sc. Dept./OOP lecture
slides 26
Nested Loops
You can nest loops of any kind one inside
another to any depth. What does this
print?
for(int i = 10; i > 0; i--) {
if (i > 7) { 6
continue; 5
} 5
while (i > 3) { 3
if(i == 5) {
break;
3
} 2
System.out.println(--i); 1
}
System.out.println(i); AU/Computer Sc. Dept./OOP lecture
} slides 27
POP QUIZ
1. In the switch statement, which types can
expression evaluate to?
char, byte, short, int
2. What must be used to separate each
section of a for statement.
semicolons
3. Which statement causes a program to skip
to the next iteration of a loop.
continue
4. Write a for loop that outputs 100-1 in
reverse sequence.

5. Write a for loop that outputs all numbers


that are divisible by 3 between 0-50.
AU/Computer Sc. Dept./OOP lecture
slides 28
Arrays

A way to organize data

AU/Computer Sc. Dept./OOP lecture


slides 29
What are Arrays?

An array is a series of compartments to


store data.

Each compartment is appropriately


sized for the particular data type the
array is declared to store.

An array can hold only one type of


data!
E.g. int[] can hold only integers
char[] can hold only
slides characters
AU/Computer Sc. Dept./OOP lecture
30
Array Visualization

Specifies an array of
variables of type int
We are creating
a new array object

int[] primes = new int[10]; // An array of 10 integers

The name of The array object is of


the array type int
and has ten elements index values

primes[0] primes[1] primes[2] primes[3] primes[4] primes[9]

AU/Computer Sc. Dept./OOP lecture


slides 31
Declaring an Array Variable

Array declarations use square


brackets.
datatype[] label;

For example:
int[] prices;
String[] names;
AU/Computer Sc. Dept./OOP lecture
slides 32
Creating a New "Empty"
Array
Use this syntax: new int[20]
The new keyword creates an array of
type int that has 20 compartments
The new array can then be assigned to
an array variable:
int[] prices = new int[20];
When first created as above, the items
in the array are initialized to the zero
value of the datatype
int: 0 double: 0.0 AU/Computer
String: null
Sc. Dept./OOP lecture
slides 33
Array Indexes
Every compartment in an array is
assigned an integer reference.

This
number is called the index of the
compartment

Important: In Java (and most other


languages), the index starts from 0 and
ends at n-1, where n is the size of the
array

AU/Computer Sc. Dept./OOP lecture


slides 34
Accessing Array Elements

To access an item in an array,


type the name of the array
followed by the item’s index in
square brackets.

For example, the expression:


names[0]
will return the first element in
the names array AU/Computer Sc. Dept./OOP lecture
slides 35
Filling an Array

Assignvalues to
compartments:

prices[0] = 6.75;
prices[1] = 80.43;
prices[2] = 10.02;

AU/Computer Sc. Dept./OOP lecture


slides 36
Constructing Arrays

 To construct an array, you can


declare a new empty array and then
assign values to each of the
compartments:

String[] names = new String[5];


names[0] = "David";
names[1] = "Qian";
names[2] = "Emina";
names[3] = "Jamal";
names[4] = "Ashenafi";
AU/Computer Sc. Dept./OOP lecture
slides 37
Another Way to Construct Arrays

You can also specify all of the items in an


array at its creation.
Use curly brackets to surround the array’s
data and separate the values with
commas:
String[] names = { "David", "Qian",
"Emina", "Jamal", "Ashenafi"};
Notethat all the items must be of the
same type. Here they are of type String.
Another example:
int[] powers = {0, 1, 10,AU/Computer
100};Sc. Dept./OOP lecture
slides 38
Length of array

String[] names = {
"David", "Qian", "Emina",
"Jamal", "Ashenafi" };
int numberOfNames = names.length;
System.out.println(numberOfNames);

Output: 5

Important: Arrays are always of the


same size: their lengths cannot be
changed once they are created!
AU/Computer Sc. Dept./OOP lecture
slides 39
Example
String[] names = {
"Aisha", "Tamara", "Gikandi", "Ato",
"Lauri"};
for(int i = 0; i < names.length; i++){
System.out.println("Hello " + names[i] + ".");
}

Output:
Hello Aisha.
Hello Tamara.
Hello Gikandi.
Hello Ato.
Hello Lauri.

AU/Computer Sc. Dept./OOP lecture


slides 40
Modifying Array Elements

Example:
names[0] = “Bekele"
Now the first name in names[] has been
changed from "Aisha" to "Bekele".
So the expression names[0] now
evaluates to "Bekele".
Note:The values of compartments can
change, but no new compartments may
be added. AU/Computer Sc. Dept./OOP lecture
slides 41
Example

int[] fibs = new int[10];


fibs[0] = 1;
fibs[1] = 1;
for(int i = 2; i < fibs.length; i++) {
fibs[i] = fibs[i-2] + fibs[i-1];
}
Note: array indexes can be expressions
Afterrunning this code, the array
fibs[] contains the first ten Fibonacci
numbers:
1 1 2 3 5 8 13 21 34 55
AU/Computer Sc. Dept./OOP lecture
slides 42
Exercise 1
 Which of the following
sequences of statements does
not create a new array?

a. int[] arr = new int[4];

b. int[] arr;
arr = new int[4];

c. int[] arr = { 1, 2, 3, 4};


just declares an array variable
d. int[] arr; AU/Computer Sc. Dept./OOP lecture
slides 43
Exercise 2
 Given this code fragment,
int[] data = new int[10];
System.out.println(data[j]);

 Which of the following is a legal


value of j?
// out of range
a. -1 // legal value
b. 0 // out of range
c. 3.5 // out of range
d. 10
AU/Computer Sc. Dept./OOP lecture
slides 44
Exercise 3
 Which set of data would not
be suitable for storing in an
array?
a. the score for each of the four
quarters of a Football match
b. your name, date// these are different
of birth, and types
score on your physics test
c. temperature readings taken every
hour throughout a day
d. your expenses each month for an
entire year AU/Computer Sc. Dept./OOP lecture
slides 45
Exercise 4

 What is the value of c after the


following code segment?

int [] a = {1, 2, 3, 4, 5};


int [] b = {11, 12, 13};
int [] c = new int[4];
for (int j = 0; j < 3; j++) {
c[j] = a[j] + b[j];
}
c = [12, 14, 16, 0]
AU/Computer Sc. Dept./OOP lecture
slides 46
2-Dimensional Arrays
 Thearrays we've used so far can be
thought of as a single row of values.
0 1
A 2-dimensional array can be thought
of as a grid (or matrix) of values
0 8 4
1 9 7
 Eachelement of the 2-D array is
accessed by providing two indexes: 2 3 6
a row index and a column index value at row index 2,
column index 0 is 3
 (A2-D array is actually just an array
of arrays)

AU/Computer Sc. Dept./OOP lecture


slides 47
2-D Array Example

 Example:
A landscape grid of a 20 x 55 acre piece of land:
We want to store the height of the land at each
row and each column of the grid.

 We declare a 2D array two sets of square brackets:


double[][] heights = new double[20][55];

 This 2D array has 20 rows and 55 columns

 Toaccess the acre at row index 11 and column index


23 user: heights[11][23]
AU/Computer Sc. Dept./OOP lecture
slides 48

You might also like