chapter 1 nested control structures

55
Khirulnizam Abd Rahman 0129034614 (WhatsApp/SMS) [email protected] KERUL.net Fundamentals of (Java) Programming

Upload: khirulnizam-abd-rahman

Post on 03-Jul-2015

1.019 views

Category:

Education


1 download

DESCRIPTION

Chapter 1 Nested Control Structures Advanced control structures in Java. java, selection, repitition

TRANSCRIPT

Page 1: Chapter 1 Nested Control Structures

Khirulnizam Abd Rahman0129034614 (WhatsApp/SMS)

[email protected]

Fundamentals of (Java) Programming

Page 2: Chapter 1 Nested Control Structures

About KhirulnizamLecturer of Computer Science, Faculty of Information Science and

Technology, Selangor International Islamic University College (KUIS) – since 2000.

Codes in blog.kerul.netProgramming background: C, Java, PHP.Apps in Google Play

M-Mathurat – 200K ( bit.ly/m-mathurat )Peribahasa Dictionary – 20K ( bit.ly/pbahasa)mDictionary – open-sourced ( bit.ly/m-dictionary )Hijrah Rasul – bit.ly/hijrah-rasulSmartSolat – bit.ly/smartsolat

Apps in Windows StoreHijrah Rasul – bit.ly/hijrah-enPeribahasa Dictionary

11/28/14http://blog.kerul.net2

Page 3: Chapter 1 Nested Control Structures

Course SynopsisThis course is the continuation of the previous course (Algorithm and Problem Solving). It introduces complex flow control, method, array, class design, file and file I/O.

Objectives: At the end of this course, students should be able to;write and apply complex control structure.create and invoke methods in programs.declare, create and apply arrays and classes.retrieve from and write data into another file.

Java Programming: From Problem Analysis to Program Design, 3e3

Page 4: Chapter 1 Nested Control Structures

Assessment

Java Programming: From Problem Analysis to Program Design, 3e4

Page 5: Chapter 1 Nested Control Structures

Main TextLiang Y. Daniel. Introduction to Java Programming, Eight

Edition, 2011, Pearson F. Joyce. Java Programming, 6th Edition, 2011, Course

Technology Tool: JDK & Eclipse Java IDE

Java Programming: From Problem Analysis to Program Design, 3e5

Page 6: Chapter 1 Nested Control Structures

Control Structure I

Page 7: Chapter 1 Nested Control Structures

Control StructuresA computer can process a program in three(3) ways :

Sequence (line by line)

Selection or choice (branch)

Repetition

Page 8: Chapter 1 Nested Control Structures

Sequence StructureStart at the beginning and follows the statement in order.

start

statement1

statement2

Statement-n

End

Page 9: Chapter 1 Nested Control Structures

Selection StructureStatement executions is depending on one or more condition

start

statement1

statement2

Statement-n

End

conditionstatement3 TF

Page 10: Chapter 1 Nested Control Structures

Repetition StructureSame statement is repeated in a number of times depending

on one or more condition.

start

statement1

statement2

Statement-n

End

conditionT

F

Page 11: Chapter 1 Nested Control Structures

Conditional ExpressionConsider the following statement

If (score is greater than or equal to 90) grade is A

If (temperature is greater than 50) display “Its Hot”

Conditional expression

Grade is A only if score >=90

Display Its Hot only if the temperature > 50

Page 12: Chapter 1 Nested Control Structures

Logical ExpressionWrite the logical expression for the following

1. yourAge is greater than 50.2. The value of myAge is not 0.3. y is between 20 and 1004. height is between 1.5 and 2.0.

Page 13: Chapter 1 Nested Control Structures

Logical ExpressionUse Logical & comparison operator to construct thelogical expression

1. yourAge > 502. myAge != 03. y > 20 && y <1004. height > 1.5 && height < 2.0.

Page 14: Chapter 1 Nested Control Structures

Logical ExpressionEvaluate the following expression. Given x is 5 and y is

200.

1. x != 12 2. y < 100 3. x == 5 4. y == x*40 5. x >=5 && x <=56. y == 200 || y ==1007. x == 10 || x != 5

Page 15: Chapter 1 Nested Control Structures

Logical ExpressionEvaluate the following expression. Given x is 5 and y is 200.

1. x != 12 2. y < 100 3. x == 5 4. y == x*40 5. x >=5 && x <=56. y == 200 || y ==1007. x == 10 || x != 5

Page 16: Chapter 1 Nested Control Structures

Selection Structure

There are 2 types of Selection Structure

If statement

Switch statement

Page 17: Chapter 1 Nested Control Structures

Selection Structure – If Statement

There are 3 types of if statement

One-way selection : if

Two-way selection : if - else

Multiple-way selection : if – else if - else

Page 18: Chapter 1 Nested Control Structures

If Statement : One-Way IFThe Syntax

If (condition)statement;

if (condition) {

statement1;statement2;

}

Only one statement

More than one statement

Page 19: Chapter 1 Nested Control Structures

If Statement : One-Way If

If (condition)statement1;

statement2;

T F

If (mark > 50) System.out.println(“GOOD!!”);System.out.println(“THANK YOU”);

F

Output :

THANK YOU

Mark = 34

Page 20: Chapter 1 Nested Control Structures

If Statement : One-Way If

If (condition)statement1;

statement2;

T F

If (mark > 50) System.out.println(“GOOD!!”);System.out.println(“THANK YOU”);

Mark = 60T

Output :

GOOD!!THANK YOU

Page 21: Chapter 1 Nested Control Structures

If Statement : One-Way If

If (mark > 50){ System.out.println(“GOOD!!”); System.out.println(“GRAGE = A!!”);}System.out.println(“THANK YOU”);

Mark = 45F

Output :

THANK YOU

Page 22: Chapter 1 Nested Control Structures

If Statement : One-Way If

If (mark > 50){ System.out.println(“GOOD!!”); System.out.println(“GRAGE = A!!”);}System.out.println(“THANK YOU”);

Mark = 60T

Output :

GOOD!!GRADE = ATHANK YOU

Page 23: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (condition)statement1;

else

statement2;

statement3;

Only one statement for each

Page 24: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (score > 50)System.out.println(“GOOD!!”);

else System.out.println(“BAD!!”);System.out.println(“THANK YOU”);

Mark = 34F

Output :

BAD!!THANK YOU

Page 25: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (score > 50)System.out.println(“GOOD!!”);

else System.out.println(“BAD!!”);System.out.println(“THANK YOU”);

Mark = 60T

Output :

GOOD!!THANK YOU

Page 26: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (condition) {

statement1;statement2;

} else{Statement3; Statement4;

} Statement5;

More than one statement

Page 27: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (score > 50){ System.out.println(“GOOD!!”);

System.out.println(“GRADE = A!!”);}else

System.out.println(“BAD!!”);

System.out.println(“THANK YOU”);

Mark = 60T

Output :GOOD!!GRADE = ATHANK YOU

Page 28: Chapter 1 Nested Control Structures

If Statement : Two-Way IFThe Syntax

if (score > 50){ System.out.println(“GOOD!!”);

System.out.println(“GRADE = A!!”);}

else

System.out.println(“BAD!!”);

System.out.println(“THANK YOU”);

Mark = 40F

Output :BAD!!THANK YOU

Page 29: Chapter 1 Nested Control Structures

If Statement : Multiple-Way IFThe Syntaxif (condition) statement1;else if (condition){

statement2; statement3;}else if (condition) statement4;else if (condition)

statement5;else {

statement6; statement7;}

Use braces if there are more than one statement in a group

Page 30: Chapter 1 Nested Control Structures

If Statement : Multiple-Way IFThe Syntaxif (mark > 70) grade = “A”;else if (mark > 60 && mark <= 70){

grade = “B”; mark = mark + 3;}else if (mark > 50 && mark <=60) grade = “C”;else if (mark > 35 && mark <=50)

grade = “D”;else {

grade = “F” message = “FAIL!!!”}

Don’t use 60 < mark <=70 x

Page 31: Chapter 1 Nested Control Structures

If Statement : Multiple-Way IF

if (mark > 70) grade = “A”;else if (mark > 60 && mark <= 70){

grade = “B”; mark = mark + 3;}else if (mark > 50 && mark <=60) grade = “C”;else if (mark > 35 && mark <=50)

grade = “D”;else {

grade = “F” message = “FAIL!!!”}System.out.println(“Grade = “ + grade);

Mark = 34?F

F

F

T

Output :Grade = F

Page 32: Chapter 1 Nested Control Structures

If Statement : Multiple-Way IF

if (mark > 70) grade = “A”;else if (mark > 60 && mark <= 70){

grade = “B”; mark = mark + 3;}else if (mark > 50 && mark <=60) grade = “C”;else if (mark > 35 && mark <=50)

grade = “D”;else {

grade = “F” message = “FAIL!!!”}System.out.println(“Grade = “ + grade);

Mark = 65?F

T

Output :Grade = B

Page 33: Chapter 1 Nested Control Structures

Selection Structure : Switchswitch(expression) { //start switch

case value1:statement1;break;

case value2:statement2;statement3;break;

case value3:statement4;break;

… default:

statement-n;} // end switch

use colon not semicolon

Page 34: Chapter 1 Nested Control Structures

Selection Structure : Switchswitch(month) { //start switch

case 1:Name = “January”;break;

case 2:name = “February”;break;

case 3:name = “March”;break;

… default:

name = “ Not available”;} // end switchSystem,out.println(“Month = “ + name);

Month = 2F

T

Page 35: Chapter 1 Nested Control Structures

C1 - COMPLEX FLOW CONTROL

FUNDAMENTALS OF PROGRAMMINGDTCP 2023

Page 36: Chapter 1 Nested Control Structures

NESTED IF STATEMENT

SYNTAX

if (Boolean_Expression_1) if (Boolean_Expression_2)

Statement_1)else

Statement_2

Page 37: Chapter 1 Nested Control Structures

Nested Statements

Subtly different forms

First Form

if (a > b){ if (c > d) e = f}else g = h;

Second Form

if (a > b) if (c > d) e = f else g = h;

// oops

Page 38: Chapter 1 Nested Control Structures

Nested if statement

What is the output? Any difference??? if ( x < y)

if (x < z)

System.out.println("Hello");

else

System.out.println("Good bye");

if ( x < y){ if (x < z) System.out.println("Hello"); }else System.out.println("Good bye");

No output given

Good bye

Page 39: Chapter 1 Nested Control Structures

The Nested-if StatementThe then and else block of an if statement can contain any valid

statements, including other if statements. An if statement containing another if statement is called a nested-if statement.

39

if (testScore >= 70) {

if (studentAge < 10) {

System.out.println("You did a great job");

} else {

System.out.println("You did pass"); //test score >= 70

} //and age >= 10

} else { //test score < 70

System.out.println("You did not pass");

}

Page 40: Chapter 1 Nested Control Structures

Control Flow of Nested-if Statement

40

messageBox.show("You did not pass");

messageBox.show("You did not pass");

false inner if

messageBox.show("You did pass");

messageBox.show("You did pass");

false

testScore >= 70 ?

testScore >= 70 ?

true

studentAge < 10 ?

studentAge < 10 ?

messageBox.show("You did a great job");

messageBox.show("You did a great job");

true

Page 41: Chapter 1 Nested Control Structures

Nested if-else Statements

An if-else statement can contain any sort of statement within it.

In particular, it can contain another if-else statement.An if-else may be nested within the "if" part.An if-else may be nested within the "else" part.An if-else may be nested within both parts.

Page 42: Chapter 1 Nested Control Structures

Nested Statements

Syntaxif (Boolean_Expression_1) if (Boolean_Expression_2)

Statement_1) else

Statement_2)else if (Boolean_Expression_3)

Statement_3) else

Statement_4);

Page 43: Chapter 1 Nested Control Structures

Nested Statements

Each else is paired with the nearest unmatched if.If used properly, indentation communicates which if goes

with which else.Braces can be used like parentheses to group statements.

Page 44: Chapter 1 Nested Control Structures

TRACE THE OUTPUT

public class test{ public static void main(String[] args){

int a=4; for (int i=1; i<a;i++ ){ for (int j=1; j<=i;j++ ){ System.out.print("*"); } System.out.println(""); }}

******

Page 45: Chapter 1 Nested Control Structures

EXERCISEConstruct a simple program that apply nested if else statement

follow the rules given.

Example: If student score is 99 then display the grade which is A to student.

Score Grade

90 <= score A

80 <= score < 90 B

70 <= score < 80 C

60 <= score < 70 D

Score < 60 F

Page 46: Chapter 1 Nested Control Structures

46

Nested if StatementsThe statement executed as a result of an if statement or else clause could be another if statement

These are called nested if statements

See MinOfThree.java (page 227)

An else clause is matched to the last unmatched if (no matter what the indentation implies)

Braces can be used to specify the if statement to which an else clause belongs

Page 47: Chapter 1 Nested Control Structures

Nested Control Structuresfor loops can be found within other for loops

47

Page 48: Chapter 1 Nested Control Structures

Example 1

for (int i = 1; i <= 5; i++){ for (int j = 1; j <= i; j++) System.out.print(" *");

System.out.println();}

48

Output:

***************

Page 49: Chapter 1 Nested Control Structures

Example 2What will be the value of after each of the following nested

loops is executed?

for (int i = 1; i < 4; i++){ for (int j = 1; j < 4-i; j++){

System.out.print(" *"); } System.out.println();}

49

Output:***

Page 50: Chapter 1 Nested Control Structures

Example 3What will be the value of after each of the following nested

loops is executed?

int sum = 0;for (int i = 0; i<=2; i++){ for (int j = 0; j<=2; j++) { sum = sum + i; }}System.out.println(sum);

50

Output:9

Page 51: Chapter 1 Nested Control Structures

Example 4What does the following program segment print?

for (int f = 0; f < 3; ++f){ for (int g = 0; g < 2; ++g){

System.out.print(f);System.out.print(g);

}}

51

Output:000110112021

Page 52: Chapter 1 Nested Control Structures

Nested LoopsSuppose you wanted to print the following table:

for (int row = 1; row <= 4; row++) { // For each of 4 rows for (int col = 1; col <= 9; col++) // For each of 9 columns System.out.print(col * row + "\t"); // Print 36 numbers System.out.println(); // Start a new row} // for row

1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 36

• You could use a nested for loop. The outer loop prints the four rows and in each row, the inner loop prints the 9 columns.

Page 53: Chapter 1 Nested Control Structures

Nested Loops (cont.)The table shows the relationship between the row and

column variables needed to print the following triangular pattern:

for (int row = 1; row <= 5; row++) { // For each row for (int col = 1; col <= 6 - row; col++) // Print the row System.out.print('#'); System.out.println(); // And a new row} // for row

# # # # ## # # ## # ## ##

• You could use the following nested for loop.

Row Column Bound(6 – Row)

Number ofSymbols

1 6-1 52 6-2 43 6-3 34 6-4 25 6-5 1

Page 54: Chapter 1 Nested Control Structures

54

The Nested-for StatementNesting a for statement inside another for statement is commonly

used technique in programming.Let’s generate the following table using nested-for statement.

Page 55: Chapter 1 Nested Control Structures

55

Generating the Tableint price;

for (int width = 11; width <=20, width++){

for (int length = 5, length <=25, length+=5){

price = width * length * 19; //$19 per sq. ft.

System.out.print (“ “ + price);

}

//finished one row; move on to next row

System.out.println(“”);

}

INNER

OUTER