1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators.

Slides:



Advertisements
Similar presentations
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
Advertisements

 2002 Prentice Hall. All rights reserved Control Structures 3 control structures –Sequential structure Built into Python –Selection structure The.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition 5.3The for Repetition Structure 5.4Examples.
Introduction to Computers and Programming Lecture 7:
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Control Structures in C++ while, do/while, for switch, break, continue.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2002 Prentice Hall. All rights reserved. 1 Chapter 3 – Control Structures Outline 3.1 Introduction 3.2 Algorithms 3.3 Pseudocode 3.4Control Structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
The University of Texas – Pan American
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition.
Chapter 5 Control Structures: Part II 1 3 Used when you know in advance how many times you want the loop to be executed. 4 Requirements: 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
1 CSCE 1030 Computer Science 1 Control Statements in Java.
 2003 Prentice Hall, Inc. All rights reserved. 1 Typecasting.
10/5: Primitives, the for loop Primitive data types –why we mention them Return to counter-controlled repetition.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
10/11: do/while, Logical Operators the revised SwitchTest.java notes on JApplets the do / while repetition structure break continue Logical operators.
Review of CIS 120 Concepts: What you said you want….
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
9/20: The while Repetition Structure last time’s program repetition structures: what they are the while repetition structure homework due on Thursday program.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1 Outline 4.1Introduction 4.2Algorithms 4.3Pseudocode 4.4Control.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
 Pearson Education, Inc. All rights reserved Control Statements: Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - JavaScript: Control Structures I Outline 8.1 Introduction 8.2 Algorithms 8.3 Pseudocode 8.4.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
1 Lecture 3 Control Structures else/if and while.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition.
2/18: Assignment Operators About Average2.java –while loop use –explicit casting –twoDigits object Assignment Operators Increment & Decrement Operators.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures.
2/25: the switch selection structure looking at Interest.java –NumberFormat –Locale –JTextArea –use of postincrement –Math.pow( rate, year ) switch.
10/4: the for loop & the switch structure Primitive data types –why we mention them Return to counter-controlled repetition.
Essentials of Counter-Controlled Repetition Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Introduction to Computers and Programming Lecture 7:
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline Counter-Controlled Repetition: Example Sentinel-Controlled Repetition:
A DVANCED P ROGRAMMING C HAPTER 5 & 6: C ONTROL S TRUCTURES Dr Shahriar Bijani Spring 2016.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
JavaScript: Control Structures I Outline 1 Introduction 2 Algorithms 3 Pseudocode 4 Control Structures 5 if Selection Structure 6 if/else Selection Structure.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Control Statements: Part 2
Chapter 4 – Control Structures Part 1
Advanced Programming Chapters 5 & 6: Control Structures
Chapter 4 - Control Structures: Part 1
Chapter 5 – Control Structures: Part 2
Chapter 5 – Control Structures: Part 2
Chapter 5 – Control Structures: Part 2
Control Statements:.
Presentation transcript:

1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators Increment and Decrement Operators Primitive Types Chapter 5 for Repetition Statement Examples Using the for Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Logical Operators Chapter 4 and 5 - Control Structures

2 Introduction We learn about Control Structures –Control structures

3 Control Structures Java has a sequence structure “built-in” Java provides three selection structures –if –If…else –switch Java provides three repetition structures –while –do…while –do Each of these words is a Java keyword

Outline 4 Average1.java gradeCounter Line 21 1 // Fig. 4.7: Average1.java 2 // Class-average program with counter-controlled repetition. 3 import javax.swing.JOptionPane; 4 5 public class Average1 { 6 7 public static void main( String args[] ) 8 { 9 int total; // sum of grades input by user 10 int gradeCounter; // number of grade to be entered next 11 int grade; // grade value 12 int average; // average of grades String gradeString; // grade typed by user // initialization phase 17 total = 0; // initialize total 18 gradeCounter = 1; // initialize loop counter // processing phase 21 while ( gradeCounter <= 10 ) { // loop 10 times // prompt for input and read grade from user 24 gradeString = JOptionPane.showInputDialog( 25 "Enter integer grade: " ); // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29 Declare variables; gradeCounter is the counter Continue looping as long as gradeCounter is less than or equal to 10

Outline 5 Average1.java 30 total = total + grade; // add grade to total 31 gradeCounter = gradeCounter + 1; // increment counter } // end while // termination phase 36 average = total / 10; // integer division // display average of exam grades 39 JOptionPane.showMessageDialog( null, "Class average is " + average, 40 "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the program } // end main } // end class Average1

Outline 6 Average1.java

Outline 7 Average2.java 1 // Fig. 4.9: Average2.java 2 // Class-average program with sentinel-controlled repetition. 3 import java.text.DecimalFormat; // class to format numbers 4 import javax.swing.JOptionPane; 5 6 public class Average2 { 7 8 public static void main( String args[] ) 9 { 10 int total; // sum of grades 11 int gradeCounter; // number of grades entered 12 int grade; // grade value double average; // number with decimal point for average String gradeString; // grade typed by user // initialization phase 19 total = 0; // initialize total 20 gradeCounter = 0; // initialize loop counter // processing phase 23 // get first grade from user 24 gradeString = JOptionPane.showInputDialog( 25 "Enter Integer Grade or -1 to Quit:" ); // convert gradeString to int 28 grade = Integer.parseInt( gradeString ); 29

Outline 8 Average2.java Line 31 Line // loop until sentinel value read from user 31 while ( grade != -1 ) { 32 total = total + grade; // add grade to total 33 gradeCounter = gradeCounter + 1; // increment counter // get next grade from user 36 gradeString = JOptionPane.showInputDialog( 37 "Enter Integer Grade or -1 to Quit:" ); // convert gradeString to int 40 grade = Integer.parseInt( gradeString ); } // end while // termination phase 45 DecimalFormat twoDigits = new DecimalFormat( "0.00" ); // if user entered at least one grade if ( gradeCounter != 0 ) { // calculate average of all grades entered 51 average = (double) total / gradeCounter; // display average with two digits of precision 54 JOptionPane.showMessageDialog( null, 55 "Class average is " + twoDigits.format( average ), 56 "Class Average", JOptionPane.INFORMATION_MESSAGE ); } // end if part of if...else 59 loop until gradeCounter equals sentinel value ( -1 ) Format numbers to nearest hundredth

Outline 9 Average2.java 60 else // if no grades entered, output appropriate message 61 JOptionPane.showMessageDialog( null, "No grades were entered", 62 "Class Average", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Average2

Outline 10 Analysis.java Line 19 Line 29 1 // Fig. 4.11: Analysis.java 2 // Analysis of examination results. 3 import javax.swing.JOptionPane; 4 5 public class Analysis { 6 7 public static void main( String args[] ) 8 { 9 // initializing variables in declarations 10 int passes = 0; // number of passes 11 int failures = 0; // number of failures 12 int studentCounter = 1; // student counter 13 int result; // one exam result String input; // user-entered value 16 String output; // output string // process 10 students using counter-controlled loop 19 while ( studentCounter <= 10 ) { // prompt user for input and obtain value from user 22 input = JOptionPane.showInputDialog( 23 "Enter result (1 = pass, 2 = fail)" ); // convert result to int 26 result = Integer.parseInt( input ); // if result 1, increment passes; if...else nested in while 29 if ( result == 1 ) 30 passes = passes + 1; Loop until student counter is greater than 10 Nested control structure

Outline 11 Analysis.java else // if result not 1, increment failures 33 failures = failures + 1; // increment studentCounter so loop eventually terminates 36 studentCounter = studentCounter + 1; } // end while // termination phase; prepare and display results 41 output = "Passed: " + passes + "\nFailed: " + failures; // determine whether more than 8 students passed 44 if ( passes > 8 ) 45 output = output + "\nRaise Tuition"; JOptionPane.showMessageDialog( null, output, 48 "Analysis of Examination Results", 49 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Analysis

12 Assignment Operators c = c + 3 –can be written as c += 3

13

14 Increment and Decrement Operators Unary increment operator ( ++ ) –Increment variable’s value by 1 Unary decrement operator ( -- ) –Decrement variable’s value by 1 Preincrement / predecrement operator Post-increment / post-decrement operator

15

Outline 16 Increment.java Line 13 postincrement Line 21 preincrement 1 // Fig. 4.14: Increment.java 2 // Preincrementing and postincrementing operators. 3 4 public class Increment { 5 6 public static void main( String args[] ) 7 { 8 int c; 9 10 // demonstrate postincrement 11 c = 5; // assign 5 to c 12 System.out.println( c ); // print 5 13 System.out.println( c++ ); // print 5 then postincrement 14 System.out.println( c ); // print System.out.println(); // skip a line // demonstrate preincrement 19 c = 5; // assign 5 to c 20 System.out.println( c ); // print 5 21 System.out.println( ++c ); // preincrement then print 6 22 System.out.println( c ); // print } // end main } // end class Increment Line 13 postincrements c Line 21 preincrements c

17 Primitive Types Primitive types –“building blocks” for more complicated types Java is strongly typed –All variables in a Java program must have a type

18

Outline 19 WhileCounter.ja va Line 14 Line 16 Line 18 1 // Fig. 5.1: WhileCounter.java 2 // Counter-controlled repetition. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class WhileCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialization while ( counter <= 10 ) { // repetition condition 17 g.drawLine( 10, 10, 250, counter * 10 ); 18 ++counter; // increment } // end while } // end method paint } // end class WhileCounter Increment for counter Condition tests for counter ’s final value Control-variable name is counter Control-variable initial value is 1

Outline 20 ForCounter.java Line 16 int counter = 1; Line 16 counter <= 10; Line 16 counter++; 1 // Fig. 5.2: ForCounter.java 2 // Counter-controlled repetition with the for statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class ForCounter extends JApplet { 8 9 // draw lines on applet’s background 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet // for statement header includes initialization, 15 // repetition condition and increment 16 for ( int counter = 1; counter <= 10; counter++ ) 17 g.drawLine( 10, 10, 250, counter * 10 ); } // end method paint } // end class ForCounter Condition tests for counter ’s final value Control-variable name is counter Control-variable initial value is 1 Increment for counter

Outline 21 Sum.java Line 12 1 // Fig. 5.5: Sum.java 2 // Summing integers with the for statement. 3 import javax.swing.JOptionPane; 4 5 public class Sum { 6 7 public static void main( String args[] ) 8 { 9 int total = 0; // initialize sum // total even integers from 2 through for ( int number = 2; number <= 100; number += 2 ) 13 total += number; // display results 16 JOptionPane.showMessageDialog( null, "The sum is " + total, 17 "Total Even Integers from 2 to 100", 18 JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate application } // end main } // end class Sum increment number by 2 each iteration

Outline 22 Interest.java Lines Line 18 Line 19 1 // Fig. 5.6: Interest.java 2 // Calculating compound interest. 3 import java.text.NumberFormat; // class for numeric formatting 4 import java.util.Locale; // class for country-specific information 5 6 import javax.swing.JOptionPane; 7 import javax.swing.JTextArea; 8 9 public class Interest { public static void main( String args[] ) 12 { 13 double amount; // amount on deposit at end of each year 14 double principal = ; // initial amount before interest 15 double rate = 0.05; // interest rate // create NumberFormat for currency in US dollar format 18 NumberFormat moneyFormat = 19 NumberFormat.getCurrencyInstance( Locale.US ); // create JTextArea to display output 22 JTextArea outputTextArea = new JTextArea(); // set first line of text in outputTextArea 25 outputTextArea.setText( "Year\tAmount on deposit\n" ); 26 Java treats floating-points as type double NumberFormat can format numeric values as currency Display currency values with dollar sign ($)

Outline 23 Interest.java Lines // calculate amount on deposit for each of ten years 28 for ( int year = 1; year <= 10; year++ ) { // calculate new amount for specified year 31 amount = principal * Math.pow( rate, year ); // append one line of text to outputTextArea 34 outputTextArea.append( year + "\t" + 35 moneyFormat.format( amount ) + "\n" ); } // end for // display results 40 JOptionPane.showMessageDialog( null, outputTextArea, 41 "Compound Interest", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); // terminate the application } // end main } // end class Interest Calculate amount with for statement

24 do…while Repetition Statement do…while structure –Similar to while structure –Tests loop-continuation after performing body of loop i.e., loop body always executes at least once

Outline 25 DoWhileTest.jav a Lines // Fig. 5.7: DoWhileTest.java 2 // Using the do...while statement. 3 import java.awt.Graphics; 4 5 import javax.swing.JApplet; 6 7 public class DoWhileTest extends JApplet { 8 9 // draw lines on applet 10 public void paint( Graphics g ) 11 { 12 super.paint( g ); // call paint method inherited from JApplet int counter = 1; // initialize counter do { 17 g.drawOval( counter * 10, counter * 10, 18 counter * 20, counter * 20 ); 19 ++counter; 20 } while ( counter <= 10 ); // end do...while } // end method paint } // end class DoWhileTest Oval is drawn before testing counter ’s final value

26 switch Multiple-Selection Statement switch statement –Used for multiple selections

Outline 27 SwitchTest.java Lines 16-21: Getting user’s input 1 // Fig. 5.9: SwitchTest.java 2 // Drawing lines, rectangles or ovals based on user input. 3 import java.awt.Graphics; 4 5 import javax.swing.*; 6 7 public class SwitchTest extends JApplet { 8 int choice; // user's choice of which shape to draw 9 10 // initialize applet by obtaining user's choice 11 public void init() 12 { 13 String input; // user's input // obtain user's choice 16 input = JOptionPane.showInputDialog( 17 "Enter 1 to draw lines\n" + 18 "Enter 2 to draw rectangles\n" + 19 "Enter 3 to draw ovals\n" ); choice = Integer.parseInt( input ); // convert input to int } // end method init // draw shapes on applet's background 26 public void paint( Graphics g ) 27 { 28 super.paint( g ); // call paint method inherited from JApplet for ( int i = 0; i < 10; i++ ) { // loop 10 times (0-9) 31 Get user’s input in JApplet

Outline 28 SwitchTest.java Line 32: controlling expression Line 32: switch statement Line switch ( choice ) { // determine shape to draw case 1: // draw a line 35 g.drawLine( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case case 2: // draw a rectangle 39 g.drawRect( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 41 break; // done processing case case 3: // draw an oval 44 g.drawOval( 10 + i * 10, 10 + i * 10, i * 10, 50 + i * 10 ); 46 break; // done processing case default: // draw string indicating invalid value entered 49 g.drawString( "Invalid value entered", 50 10, 20 + i * 15 ); } // end switch } // end for } // end method paint } // end class SwitchTest default case for invalid entries switch statement determines which case label to execute, depending on controlling expression user input ( choice ) is controlling expression

Outline 29 SwitchTest.java

Outline 30 SwitchTest.java

31 Fig switch multiple-selection statement activity diagram with break statements. case a action(s) break default action(s) [ true ] case b action(s) break case z action(s) break [ false ] case a [ true ] case b case z [ false ]

32 break and continue Statements break statement –Causes immediate exit from control structure Used in while, for, do…while or switch statements continue statement –Skips remaining statements in loop body –Proceeds to next iteration Used in while, for or do…while statements

Outline 33 BreakTest.java Line 12 Lines // Fig. 5.11: BreakTest.java 2 // Terminating a loop with break. 3 import javax.swing.JOptionPane; 4 5 public class BreakTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; 10 int count; for ( count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 15 break; // terminate loop output += count + " "; } // end for output += "\nBroke out of loop at count = " + count; 22 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class BreakTest Loop 10 times exit for structure ( break ) when count equals 5

Outline 34 ContinueTest.ja va Line 11 Lines // Fig. 5.12: ContinueTest.java 2 // Continuing with the next iteration of a loop. 3 import javax.swing.JOptionPane; 4 5 public class ContinueTest { 6 7 public static void main( String args[] ) 8 { 9 String output = ""; for ( int count = 1; count <= 10; count++ ) { // loop 10 times if ( count == 5 ) // if count is 5, 14 continue; // skip remaining code in loop output += count + " "; } // end for output += "\nUsed continue to skip printing 5"; 21 JOptionPane.showMessageDialog( null, output ); System.exit( 0 ); // terminate application } // end main } // end class ContinueTest Loop 10 timesSkip line 16 and proceed to line 11 when count equals 5

35 Logical Operators Logical operators –Allows for forming more complex conditions –Combines simple conditions Java logical operators –&& (conditional AND) –& (boolean logical AND) –|| (conditional OR) –| (boolean logical inclusive OR) –^ (boolean logical exclusive OR) –! (logical NOT)