Control Structures (Deitel chapter 4,5)

Similar documents
Chapter 4 Control Structures: Part 2

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements. Musa M. Ameen Computer Engineering Dept.

Chapter 5 Control Structures: Part 2

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Chapter 3 Structured Program Development

Structured Program Development in C

Fundamentals of Programming Session 7

Chapter 3 Structured Program Development in C Part II

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

Structured Program Development

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Course PJL. Arithmetic Operations

JavaScript: Control Statements I Pearson Education, Inc. All rights reserved.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

In this chapter you will learn:

Copyright 1999 by Deitel & Associates, Inc. All Rights Reserved.

Chapter 2 - Control Structures

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Chapter 2 - Control Structures

Chapter 4 C Program Control

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Control Structures II. Repetition (Loops)

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Computer Programming I - Unit 5 Lecture page 1 of 14

LECTURE 5 Control Structures Part 2

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 2 - Control Structures

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Lecture 7 Tao Wang 1

Introduction. C provides two styles of flow control:

Introduction to the Java Basics: Control Flow Statements

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

Why Is Repetition Needed?

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 2 - Control Structures

CS110D: PROGRAMMING LANGUAGE I

C++ Programming: From Problem Analysis to Program Design, Third Edition

Day06 A. Young W. Lim Mon. Young W. Lim Day06 A Mon 1 / 16

CS171:Introduction to Computer Science II

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Arrays (Deitel chapter 7)

Control Statements: Part 1

CS 106 Introduction to Computer Science I

Chapter 3 - Introduction to Java Applets

Chapter 4 C Program Control

Structured Programming. Dr. Mohamed Khedr Lecture 9

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

Dept. of CSE, IIT KGP

Programming for Engineers Iteration

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Course overview: Introduction to programming concepts

1 EEE1008 C Programming

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Control Structures of C++ Programming (2)

A Look Back at Arithmetic Operators: the Increment and Decrement

3chapter C ONTROL S TATEMENTS. Objectives

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Loops. CSE 114, Computer Science 1 Stony Brook University

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

C++ PROGRAMMING SKILLS Part 2 Programming Structures

Chapter 2. Elementary Programming

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Repetition, Looping. While Loop

א א א E2-1F Welcome to Java Programming!

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Second Term ( ) Department of Computer Science Foundation Year Program Umm Al Qura University, Makkah

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

CS 106 Introduction to Computer Science I

Chapter 5: Control Structures II (Repetition)

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

REPETITION CONTROL STRUCTURE LOGO

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

BITG 1233: Introduction to C++

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Java Basic Programming Constructs

Example: Monte Carlo Simulation 1

TTh 9.25 AM AM Strain 322

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Transcription:

Control Structures (Deitel chapter 4,5) 1

2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement switch Multiple-Selection Statement break and continue Statements Structured Programming Summary

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

4 if Single-Selection Statement Single-entry/single-exit control structure Perform action only when condition is true Action/decision programming model [grade >= 60] print Passed [grade < 60] if single-selections statement activity diagram.

5 if else Selection Statement Perform action only when condition is true Perform different specified action when condition is false Conditional operator (?:) System.out.println( grade >= 60? Passed : Failed ); print Failed [grade < 60] [grade >= 60] print Passed if else double-selections statement activity diagram.

while Repetition Statement 6 Repeat action while condition remains true merge decision [product <= 1000] double product value [product > 1000] Corresponding Java statement: product = 2 * product; while repetition statement activity diagram.

Formulating Algorithms 7 Counter-controlled repetition Variable that controls number of times set of statements executes Sentinel-controlled repetition User enters sentinel value (-1) to end repetition

1 // Fig. 4.7: Average1.java 2 // Class-average program with counter-controlled repetition. 3 import javax.swing.joptionpane; 4 5 public class Average1 { Declare variables; 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 13 14 String gradestring; // grade typed by user 15 16 // initialization phase 17 total = 0; // initialize total 18 gradecounter = 1; // initialize loop counter 19 20 // processing phase 21 while ( gradecounter <= 10 ) { // loop 10 times 22 23 // prompt for input and read grade from user 24 gradestring = JOptionPane.showInputDialog( 25 "Enter integer grade: " ); 26 27 // convert gradestring to int 28 grade = Integer.parseInt( gradestring ); 29 gradecounter is the counter Continue looping as long as gradecounter is less than or equal to 10 Outline Average1.java gradecounter Line 21 8

30 total = total + grade; // add grade to total 31 gradecounter = gradecounter + 1; // increment counter 32 33 } // end while 34 35 // termination phase 36 average = total / 10; // integer division 37 38 // display average of exam grades 39 JOptionPane.showMessageDialog( null, "Class average is " + average, 40 "Class Average", JOptionPane.INFORMATION_MESSAGE ); 41 42 System.exit( 0 ); // terminate the program 43 44 } // end main 45 46 } // end class Average1 Outline Average1.java 9

Outline 10 Average1.java

11 Compound Assignment Operators Assignment Operators Abbreviate assignment expressions Any statement of form variable = variable operator expression; Can be written as variable operator= expression; e.g., addition assignment operator += c = c + 3 can be written as c += 3

12 A ssig nm e nt operator Sa m p le expression Explanation Assig ns Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; += c += 7 c = c + 7 10 to c -= d -= 4 d = d - 4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g Fig. 4.12 A rithm e tic a ssig nm e nt o p e ra to rs.

13 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

14 Operator Ca lled Sa m p le expression Explanation ++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides. ++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1. -- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides. -- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1. Fig. 4.13 The increment and decrement operators.

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 6 15 16 System.out.println(); // skip a line 17 18 // 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 6 23 24 } // end main 25 26 } // end class Increment 5 5 6 Line 13 postincrements c Line 21 preincrements c Outline 15 Increment.java Line 13 postincrement Line 21 preincrement 5 6 6

for Repetition Statement 16 Handles counter-controlled-repetition details for keyword Control variable Required semicolon separator Final value of control variable for which the condition is true Required semicolon separator for ( int counter = 1; counter <= 10; counter++ ) Initial value of control variable Loop-continuation condition Increment of control variable

for Repetition Structure (cont.) 17 for ( initialization; loopcontinuationcondition; increment ) statement; can usually be rewritten as: initialization; while ( loopcontinuationcondition ) { statement; increment; }

18 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 action state condition [true] [false] do while repetition statement activity diagram.

19 switch Multiple-Selection Statement switch statement Used for multiple selections case a [false] [true] case a action(s) break case b [false] [true] case b action(s) break. case z [false] [true] case z action(s) break default action(s) switch multiple-selection statement activity diagram with break statements.

32 switch ( choice ) { // determine shape to draw 33 34 case 1: // draw a line 35 g.drawline( 10, 10, 250, 10 + i * 10 ); 36 break; // done processing case 37 38 case 2: // draw a rectangle 39 g.drawrect( 10 + i * 10, 10 + i * 10, 40 50 + i * 10, 50 + i * 10 ); 41 break; // done processing case 42 43 case 3: // draw an oval 44 g.drawoval( 10 + i * 10, 10 + i * 10, 45 50 + i * 10, 50 + i * 10 ); 46 break; // done processing case 47 48 default: // draw string indicating invalid value entered 49 g.drawstring( "Invalid value entered", 50 10, 20 + i * 15 ); 51 52 } // end switch 53 54 } // end for 55 56 } // end method paint 57 58 } // end class SwitchTest Outline user input (choice) is switch controlling statement expression determines which case label to execute, SwitchTest.java depending on controlling expression Line 32: controlling expression Line 32: switch statement Line 48 default case for invalid entries 20

21 break and continue Statements break/continue Alter flow of control 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

22 Structured Programming Summary Sequence structure built-in to Java Selection structure if, if else and switch Repetition structure while, do while and for

Sequence Selection 23 if statement (single selection) switch statement (multiple selection) [f] [t] [f] [t] break [t] break if else statement (double selection). [f] [t] [f] [t] break default Repetition while statement do while statement for statement [f] [t] [f] [t] [f] [t] Java s single-entry/single-exit sequence, selection and repetition statements.