Control Structures: if and while A C S L E C T U R E 4

Similar documents
Oct Decision Structures cont d

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

Loops. CSE 114, Computer Science 1 Stony Brook University

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

CMPT 125: Lecture 4 Conditionals and Loops

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

Java I/O and Control Structures

Chapter 4: Conditionals and Recursion

Top-Down Program Development

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Algorithms and Conditionals

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Java I/O and Control Structures Algorithms in everyday life

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

STUDENT LESSON A12 Iterations

Handout 4 Conditionals. Boolean Expressions.

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

CSC 1051 Data Structures and Algorithms I

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Flow Control. Key Notion. Statement Categories. 28-Oct-10

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Last Class. While loops Infinite loops Loop counters Iterations

1 Short Answer (15 Points Each)

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

1 Short Answer (5 Points Each)

Lesson 7 Part 2 Flags

1 Short Answer (10 Points Each)

CSC 1051 Data Structures and Algorithms I

Chapter 4: Control structures. Repetition

Chapter 2. Elementary Programming

Chapter 3. Selections

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Loops. Repeat after me

Java Classes: Math, Integer A C S L E C T U R E 8

Flow of Control. Chapter 3

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Chapter 4: Control structures

H212 Introduction to Software Systems Honors

Program Control Flow

Program Control Flow

Elementary Programming

Decisions (If Statements) And Boolean Expressions

Java Coding 3. Over & over again!

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Programming with Java

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

CEN 414 Java Programming

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

1 Short Answer (10 Points Each)

Flow of Control. Chapter 3

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

JAVA OPERATORS GENERAL

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Chapter 3: Program Statements

Flow of Control: Loops. Chapter 4

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

CS111: PROGRAMMING LANGUAGE II

Example: Monte Carlo Simulation 1

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Data Structures and Algorithms I

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CT 229 Java Syntax Continued

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Combo Lecture Lecture 14/15. Instructor: Craig Duckett

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Following is the general form of a typical decision making structure found in most of the programming languages:

Arrays. Eng. Mohammed Abdualal

CS 101 Fall 2006 Midterm 3 Name: ID:

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

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

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

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

CS 101 Spring 2007 Midterm 2 Name: ID:

McGill University School of Computer Science COMP-202A Introduction to Computing 1

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Introduction to Java & Fundamental Data Types

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Chapter 4: Control Structures I

Control Flow Statements

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

AP Computer Science Unit 1. Programs

Final Exam Practice. Partial credit will be awarded.

CSC141, Computer Science I, Instructor: Dr. Zhen Jiang, Test 2

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Full file at

MEHMET YAYAN - İSMAİL HAKKI ÖZTÜRK CS101/SEC.-2 CLASS NOTES 1. March 28-30, 2007

Transcription:

Control Structures: if and while A C S - 1903 L E C T U R E 4

Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator Loops while, do while, for, enhanced for (later)

Compound statement A compound statement is often used with ifs, whiles etc. to provide a group of statements to be executed repeatedly or conditionally. opening brace closing brace { } temp = x; x = y; y = temp;

Decision structures : the if statement An if statement is coded with a logical expression and either one statement (statement) or two statements (statement 1 and statement 2 ) if (logical expression) statement 1 else statement The else clause is optional 2 We say the if is a decision structure based on the outcome of evaluating the logical expression one of possibly two statements is executed.

Logical expressions if (logical expression)... A logical expression is an expression that evaluates true or false. Suppose a, b, q, i, j are integers and found is boolean. Examples of logical expressions: a < b a < b b < c a+5 >= q*3 found && i<100 a == b i < 100 && j < 100 a!= b!found && i < 100 found! found

Decision structures : the if statement if (logical expression) statement 1 else statement 2 When an if executes the logical expression is evaluated and: when the expression evaluates to true, statement 1 executes execution of program statements continue at the statement following the if; when the expression evaluates to false, statement 2 executes execution of program statements continue at the statement following the if.

Example 1 Get a number from the user and display positive or not positive accordingly int number = keyboard.nextint(); System.out.print("the number " +number+ " is "); // Display a message if number is positive or not if (number > 0) { System.out.println("positive"); } else { System.out.println("not positive"); } Indented code this is practice we will follow PositiveOrNot.java Only one of these can execute

Example 2 The Canadian SIN can be tested for a proper check digit. Part of the process involves multiplying individual digits by either 1 or 2. When a digit is multiplied by 2 and the result is greater than 9 then the two digits of this product must be added. For example, if the digit is 8 then the product 2*8 is 16. 16 is greater than 9 and so the sum of its digits is calculated 1+6 is 7 Along these lines consider a simpler program that: 1. gets a digit from the user 2. multiplies that digit by 2 3. if the product is <= 9 then displays the digit otherwise displays the sum of the digits of the product

Example 2 import java.util.scanner; TestGreaterThanNine.java public class TestGreaterThanNine { public static void main(string[] args) { Scanner kb = new Scanner(System.in); System.out.println("Please enter a single digit:"); int digit = kb.nextint(); int result = digit*2; } } if (result > 9) { result = result/10 + result%10; } System.out.println(" result is " +result); The else clause is not necessary; omitted

Nested ifs statement 1 or statement 2 can be any Java statement statement 1, statement 2 can be ifs or other control structures We can nest one control structure inside another control structure

Nested ifs: example 1 Suppose we must handle a purchase transaction in one of two ways: 1. If the customer pays cash we must round up/down as there are no pennies. 2. If the customers pays by electronic means there is a surcharge of 25 cents.

Nested ifs: example 1 In pseudocode: 1. obtain the type and amount of the purchase 2. if the purchase is cash then round the cost up/down 3. otherwise add on the surcharge 4. display the total cost for the customer Steps 2 and 3 can be handled with an if-else can be handled with a nested if-else

Nested ifs: example 1 RoundCostUpDown.java if (typepayment.equals("cash")) { if (originalcost % 5 < 3) actualcost = originalcost - originalcost%5; else actualcost = originalcost + (5 - originalcost%5); } else actualcost = originalcost + 25; Note the indentation Nested if to handle rounding for a cash payment

Nested ifs: example 2 A table for converting alphabetic grades to a numeric value: Letter grade Numeric grade A 4 B 3 C 2 D 1 F 0 When you need to convert some letter grade to its equivalent numeric value you would look for which row the letter appears in and read off the numeric value in that same row. E.g. the numeric value corresponding to B is 3

Nested ifs: example 2 To program this conversion, nested ifs are useful Letter grade Numeric grade A 4 B 3 C 2 D 1 F 0 We can structure this code in many ways We will consider 3 ways to write the logic

Option 1 LetterGradeToNumericGrade1.java if (lettergrade.equals("a")) numericgrade = 4.0; if (lettergrade.equals("b")) numericgrade = 3.0; if (lettergrade.equals("c")) numericgrade = 2.0; if (lettergrade.equals("d")) numericgrade = 1.0; This style requires the evaluation of expressions that would not be necessary - e.g. when the grade is A the other ifs do not need to execute, but they do

Option 2 if (lettergrade.equals("a")) numericgrade = 4.0; else if (lettergrade.equals("b")) numericgrade = 3.0; else if (lettergrade.equals("c")) numericgrade = 2.0; else if (lettergrade.equals("d")) numericgrade = 1.0; else numericgrade = 0.0; This style uses indentation properly - each if is indented within the outer if - but the code easily goes off the page/screen and gets hard to read LetterGradeToNumericGrade2.java

Option 3 if (lettergrade.equals("a")) numericgrade = 4.0; else if (lettergrade.equals("b")) numericgrade = 3.0; else if (lettergrade.equals("c")) numericgrade = 2.0; else if (lettergrade.equals("d")) numericgrade = 1.0; else numericgrade = 0.0; IfElseIfIndentation.java Due to the similarity of the logical conditions, this style is favourable - shows the choices at the same level of indentation

Loops: while while statement executes a statement as long as some expression is true while (logical expression) statement Recall: A logical expression is an expression that evaluates true or false.

Recall: while How a while executes:

Loops: while E.g. display the digits from 0 to 9 Numbers0to9.java int count = 0; System.out.println("Numbers"); while ( count < 10 ){ System.out.println(count); count = count + 1; } Start of compound statement Executed repeatedly until count is 10 Indented code How can you modify this code to display numbers from 9 down to 0?

Loops: while E.g. display the digits of a positive number DisplayDigits.java while (number > 0){ int digit = number % 10; System.out.print("\t"+digit); number = number / 10; System.out.println("\t"+number); } Indented code Start of compound statement Executed repeatedly as long as number > 0 How can you modify this code to calculate the sum of an integer s digits?

Loops: nesting whiles A while can contain another while e.g. displaying a times table 1 2 3 4 1 1 2 3 4 2 2 4 6 8 3 3 6 9 12 4 4 8 12 16

Loops: nesting whiles To produce a times table, use one loop inside another. We say one loop is nested inside the other loop. To begin: we will just produce a simple vertical listing of i, j, i*j where i varies from 1 to 4 and j varies from 1 to 4. Ultimately we want a listing like that shown on previous slide.

Loops: nesting whiles public class NestedWhiles { public static void main(string[] args) { int i, j; System.out.println( "\ti\tj\ti*j" ); // i takes on values 1,2,3,4 i = 1; while (i < 5){ j = 1; // j takes on values 1,2,3,4 while (j < 5){ System.out.println( "\t"+i+"\t"+j+"\t"+(i*j)); j = j + 1; } i = i + 1; } System.out.println( "program ended" ); } } NestedWhiles.java For each value of i, j takes on values 1, 2, 3, 4 One while nested inside another while

Looping: nested whiles Output from nested whiles Heading Note when i is 1 j takes on 1, 2, 3, 4 when i is 2 j takes on 1, 2, 3, 4 when i is 3 j takes on 1, 2, 3, 4 when i is 4 j takes on 1, 2, 3, 4 Times table from class: TimesTableWhile.java

Loops and autoincrement, autodecrement statements such as n = n + 1; m = m - 1; are so common in programming that languages such as Java include special operators for this purpose called autoincrement and autodecrement

Autoincrement and autodecrement n++; m--; post-increment post-decrement ++n; --m; pre-increment pre-decrement

Autoincrement and autodecrement n++; ++n; m--; --m; When autoincrement is used alone and not as part of a larger expression pre- and post-increment have the same effect - to increment the operand by 1. Similarily, when autodecrement is used alone and not as part of a larger expression pre- and post-decrement have the same effect - to decrement the operand by 1.

Autoincrement and autodecrement ASIDE: autoincrement, autodecrement within an expression post-increment and post-decrement: the operand s value is used and then the operand s value is incremented/ decremented pre-increment and pre-decrement: the operand s value is incremented/ decremented and then the operand s value is used // try this out // what is printed? int m = 1; int n = m++ + m++; System.out.println("m="+m); System.out.println("n="+n); // try this out // what is printed? int m = 1; int n = ++m + ++m; System.out.println("m="+m); System.out.println("n="+n);