Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.

Slides:



Advertisements
Similar presentations
Control Structures.
Advertisements

Control Structures Corresponds with Chapters 3 and 4.
5/17/ Programming Constructs... There are several types of programming constructs in JAVA. - If-else construct or ternary operator - while - do-while.
Topic 03 Control Statements Programming II/A CMC2522 / CIM2561 Bavy Li.
Introduction to Computers and Programming Lecture 9: For Loops New York University.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Switch Statement switch (month) { case 9: case 4: case 6: case 11: days = 30; break; case 2: days = 28; if (year % 4 == 0) days = 29; break; default: days.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
The switch Statement, DecimalFormat, and Introduction to Looping
TODAY’S LECTURE Review Chapter 2 Go over exercises.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Iteration and Simple Menus Deterministic / Non-deterministic loops and simple menus.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Chapter 4 Loops Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Lecture 4 Control Structures MIT – AITI What are Control Structures? Control structures are a way to alter the natural sequence of execution in.
Flow of Control Chapter 3 Flow of control Branching Loops
Chapter 3- Flow Control. Overview n Why flow control n Branches vs. Loops n Branch statements n Loop Statements n Complex loops n Boolean variables n.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Control statements Mostafa Abdallah
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Application development with Java Lecture 6 Rina Zviel-Girshin.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 8 Java Fundamentals Control Structures Fri.
1 Chapter 5 Control Statements. 2 Objectives F To understand the flow of control in selection and loop statements. F To use Boolean expressions to control.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Conditional Statements A conditional statement lets us choose which statement will be executed next Conditional statements give us the power to make basic.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 9 Repetition.
Lecture 4b Repeating With Loops
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Chapter 4: Control Structures I
The switch Statement, and Introduction to Looping
Statements (6 of 6) A statement causes an action to be performed by the program. It translates directly into one or more executable computer instructions.
CiS 260: App Dev I Chapter 4: Control Structures II.
Chapter 5 Repetition.
Arrays, For loop While loop Do while loop
Chapter 4: Control Structures I
Chapter 9 Control Structures.
CSC215 Lecture Flow Control.
Lab5 PROGRAMMING 1 Loop chapter4.
Java LESSON 3 Loops.
Chapter 4 - Program Control
PROGRAM FLOWCHART Iteration Statements.
Chapter 4: Loops and Iteration
Presentation transcript:

Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures

Lecture Outline – Control Structures 1. Block Statements 2. Decision Statements 3. Loops

What are Control Structures? Without control structures, a computer would evaluate all instructions in a program sequentially Allow you to control: – the order in which instructions are evaluated – which instructions are evaluated – the “flow” of the program Use pre-established code structures: – block statements (anything contained within curly brackets) – decision statements ( If, If-Else, Switch ) – Loops ( For, While )

Block Statements Statements contained within curly brackets Evaluated sequentially when given instruction to “enter” curly brackets Most basic control structure (building block of other control structures) { statement1; statement2; }

Decision Statements – If The “if” decision statement causes a program to execute a statement conditionally* if (condition) { statement; } next_statement; *Executes a statement when a condition is true

Dissecting If if (condition) { statement; } next_statement; The condition must produce either true or false, also known as a boolean value If condition returns true, statement is executed and then next_statement If condition returns false, statement is not executed and the program continues at next_statement

execute statement execute next_statement condition true ? if (condition) { statement; } next_statement; yes no If Statement Flow Chart

If Example int price = 5; if (price > 3) { System.out.println(“Too expensive”); } //continue to next statement Output: Too expensive

If-Else Statements The basic “if” statement can be extended by adding the “else” clause in order to do something if expression is false if (condition) { statement1; } else{ statement2; } next_statement; Again, the condition must produce a boolean value If condition returns true, statement1 is executed and then next_statement is executed. If condition returns false, statement2 is executed and then next_statement is executed.

condition TRUE? execute statement1 execute statement2 execute next_statement if (condition){ statement1; } else { statement2; } next_statement; no yes If-Else Statement Flow Chart

If-Else Example int price = 2; if (price > 3) { System.out.println(“Too expensive”); } else { System.out.println(“Good deal”); } //continue to next statement Output: Good deal

Chained If-Else Statements Note that you can combine if-else statements below to make a chain to deal with more than one case 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.");

Switch Statements The switch statement is another way to test several cases generated by a given expression. The expression must produce a result of type char, byte, short or int, but not long, float, or double. For example: switch (expression) { case value1: statement1; break; case value2: statement2; break; default: default_statement; break; } The break; statement tells the computer to exit the switch statement

expression equals value1 ? expression equals value2 ? Do default action Do value1 thing Do value2 thing break Continue the program switch (expression){ case value1: // Do value1 thing break; case value2: // Do value2 thing break;... default: // Do default action break; } // Continue the program y y n n Switch Statement Flow Chart

Remember the Example… Here is the example of 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.");

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."); } Here is the way to convert the chained if-else statement to a switch statement

What if there are no breaks? Without break, switch statements will execute the first statement for which the expression matches the case value AND then evaluate all other statements from that point on For example: switch (expression) { case value1: statement1; case value2: statement2; default: default_statement; } NOTE: Every statement after the true case is executed

y y n n switch (expression){ case value1: // Do value1 thing case value2: // Do value2 thing... default: // Do default action } // Continue the program expression equals value1 ? Do value1 thing Do value2 thing Do default action expression equals value2 ? Continue the program Switch Statement Flow Chart w/o breaks

A loop allows you to execute a statement or block of statements repeatedly. There are three types of loops in Java: 1. while loops 2. do-while loops 3. for loops Loops

The while Loop while (condition){ statement } This while loop executes as long as the given logical expression between parentheses is true. When condition is false, execution continues with the statement following the loop block. The condition is tested at the beginning of the loop, so if it is initially false, the loop will not be executed at all.

Test condition is true? The while loop Execute loop statement(?) Next statement While Loop Flow Chart while (expression){ statement } yes no

int limit = 4; int sum = 0; int i = 1; while (i < limit){ sum += i; i++; } What is the value of sum ? 6 Example i = 1 i = 2 i = 3 i = 4 sum = 1 sum = 3 sum = 6

do-while Loops Similar to while loop but guarantees at least one execution of the body do { statement; } while(condition )

do-while Flowchart execute statement execute next_statement condition true ? yes no do { statement; } while(condition)

do-while Example boolean test = false; do{ System.out.println(“Hey!”) } while(test) Output: Hey!

For Loop for (i = start; i <= end; i++) {... } Control structure for capturing the most common type of loop i = start; while (i <= end) {... i++; }

Dissecting the For Loop The control of the for loop appear in parentheses and is made up of three parts. 1. The first part, the initialization, sets the initial conditions for the loop and is executed before the loop starts. 2. Loop executes so long as the condition is true and exits otherwise 3. The third part of the control information, the update, is used to increment the loop counter. This is executed at the end of each loop iteration. for (initialization; condition; update) { statement; }

Initialize count The for loop Test condition is true? Increment count Execute loop statement(s) yes New statement no For-Loop Flow Chart for (initialization; condition; update) { //statement }

int limit = 4; int sum = 0; for(int i = 1; i<=limit; i++ ) { sum += i; } What is the value of sum ? 10 Example i = 1 i = 2 i = 3 i = 4 i = 5 sum = 1 sum = 3 sum = 6 sum =

for ( int div = 0; div<1000; div++ ) { if ( div % 12 == 0 ){ System.out.println(div+"is divisible by 12"); } This loop will display every number from 0 to 999 that is evenly divisible by 12. Another Example

If there is more than one variable to set up or increment they are separated by a comma. for (i=0, j=0; i*j<1000; i++, j+=2) { System.out.println(i+"*"+j+"="+i*j); } You do not have to fill every part of the control of the for loop but you must still have two semi-colons. for (int i=0; i<100; ) { sum+=i; i++; } *While these are valid uses of for loops, straying far from convention may make code difficult to understand and thus is not common Other Possibilities

Test condition is true? Execute loop statement(?) Next statement The while loop y n Initialize count Test condition is true? Execute loop statement(s) Increment count New statement The for loop y n Comparison of For and While -Loops

Using the break Statement in Loops We have seen the use of the break statement in the switch statement. In loops, you can use the break statement to exit the current loop you are in. Here is an example: int index = 0; while (index <= 4){ index++; if (index==3) break; System.out.println("The index is “ + index); } The index is 1 The index is 2 index = 1 index = 2 index = 3

Using the continue Statement in Loops Continue statement causes the loop to jump to the next iteration Similar to break, but only skips to next iteration; doesn’t exit loop completely int index = 0; while (index <= 4){ index++; if (index==3) continue; System.out.println("The index is “ + index); } The index is 1 The index is The index is 4 index = 1 index = 2 index = 3 Index = 4

Nested Loops You can nest loops of any kind inside another to any depth. Here is a example: int totalCount = 0; while(totalCount<3){ for(int i = 0; i < 2; i++){ totalCount += 1; } System.out.println(totalCount); 4 i = 0 i = 1 i = 0 i = 1 totalCount = 1 totalCount = 2 totalCount = 3 totalCount = 4

Nested Loops – Another Example Printing a triangle for (int i=1; i<=5; i++){ for (int j=1; j<=i; j++){ System.out.println(“*”); } * * * * * * * * * * * *

Control Structures Review Questions Question 1 of 3 1. You are withdrawing money from a savings account. How do you use an If Statement to make sure you do not withdraw more than you have. if ( amount < balance ) { balance = balance – amount; } //next statement

Control Structures Review Questions Question 2 of 3 2. How can you implement AbsoluteValue, a function which always returns the positive value of whatever integer it gets as input if ( number >= 0) System.out.println(number); else System.out.println(-1 * number); //next statement

Control Structures Review Questions Outputs 100  0 in reverse sequence. Question 3 of 3 3. What does the following loop do? for (int i=100; i>=0; i--) { System.out.println(i); }

Lecture Summary Block Statements – statements surrounded by curly brackets Decision Statements – If Statements – If-Else Statements Chained If-Else Statements – Switch Statements Breaks Loops – while loops – do-while Loops – for Loops – Nested Loops