GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to.

Slides:



Advertisements
Similar presentations
1 Chapter 3: Program Statements Lian Yu Department of Computer Science and Engineering Arizona State University Tempe, AZ
Advertisements

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ECE122 L8: More Conditional Statements February 7, 2007 ECE 122 Engineering Problem Solving with Java Lecture 8 More Conditional Statements.
Logical Operators and Conditional statements
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
The switch Statement, DecimalFormat, and Introduction to Looping
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
CSCI 1100/1202 January 28, The switch Statement The switch statement provides another means to decide which statement to execute next The switch.
Chapter 3: Program Statements
Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.
1 Data Comparisons and Switch Data Comparisons Switch Reading for this class: L&L 5.3,
© 2004 Pearson Addison-Wesley. All rights reserved February 17, 2006 The ‘while’ Statement ComS 207: Programming I (in Java) Iowa State University, SPRING.
© 2004 Pearson Addison-Wesley. All rights reserved February 20, 2006 ‘do’ and ‘for’ loops ComS 207: Programming I (in Java) Iowa State University, SPRING.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Flow of Control Part 1: Selection
GP3, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 3 We start at 13:00 Slides are available from the course home page Feel free to.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Switch Statements Comparing Exact Values. The Switch Statement: Syntax The switch statement provides another way to decide which statement to execute.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 The switch Statement The switch statement provides another way.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/29 The switch Statement The switch statement provides another way.
Topics Logical Operators (Chapter 5) Comparing Data (Chapter 5) The conditional operator The switch Statement The for loop Nested Loops.
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Flow of Control Chapter 3. Outline Branching Statements Java Loop Statements Programming with Loops The Type boolean.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Control statements Mostafa Abdallah
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Application development with Java Lecture 6 Rina Zviel-Girshin.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Selections Java.
Chapter 6 More Conditionals and Loops
Boolean Expressions and If
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Outline Altering flow of control Boolean expressions
Chapter 3: Program Statements
Comparing Data & the ‘switch’ Statement
Comparing Data & the ‘switch’ Statement
CprE 185: Intro to Problem Solving (using C)
Chap 7. Advanced Control Statements in Java
Conditionals and Loops
‘do’ and ‘for’ loops October 1, 2007 ComS 207: Programming I (in Java)
Control Structure.
‘do’ and ‘for’ loops October 2, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

GP4, Martin Lillholm 1 Introductory Programming (GP) Spring 2006 Lecture 4 We start at 13:00 Slides are available from the course home page Feel free to print them now Martin Lillholm

GP4, Martin Lillholm 2 Mandatory Assignment How did it go with last week’s mandatory assignment ? –Easy? –Hard? –Many didn’t hand in – why ?

GP4, Martin Lillholm 3 Last Week Classes, objects (instances) Attributes (instance variables) Methods and constructors A first look a static methods and variables (class variables) Encapsulation Object/reference variables – variable of non-primitive type The String, Random, Math og Scanner classes Formatted output

GP4, Martin Lillholm 4 The Scanner class again Input several (e.g.) integers using one line of input:

GP4, Martin Lillholm 5 Formatting Phone Numbers Assignment from last week: L&L Programming Project DecimalFormat fmt = new DecimalFormat("00000"); System.out.println(fmt.format(23));

GP4, Martin Lillholm 6 Java API Specification –Appendix M –

GP4, Martin Lillholm 7 What Have We Skipped so Far? Earlier: –Enumerated types –Wrapper classes and auto boxing –Some GUI Today: –Iterators section 5.6

GP4, Martin Lillholm 8 Today More on flow of control Boolean Expressions Relational and logical operators if and switch statements Loop statement –for, do, while Block statements Graphics using loops and conditions – if time allows

GP4, Martin Lillholm 9 How Does Today’s Chapter Fit In ? Program execution (normally) begins in the main method. Statements in the main method are executed sequentially – flow of control. Method calls causes flow of control to execute statements in the method (and possible nested method calls) and then return to the next statement in the main method. Conditional statements: Loops statement1 statement2 statement3 statement4 statement5 statement1 statement2 if (condition) statement3 // true statement4 e.g. 10 times Both used in methods bodies incl. main

GP4, Martin Lillholm 10 Boolean Expressions Boolean/logical expressions  true or false Has type boolean As opposed to arithmetic expressions  1, Has type integer, double,... Boolean expressions are normally formed using relational and logical operators.

GP4, Martin Lillholm 11 OperatorMeaningExample <Less than x < 60 <=Less than or equal x <= 60 >Greater than x > 60 >=Greater than or equal x >= 60 ==Equal to x == 60 !=Not equal to x != 60 Relational Operators Argument type typically integer, double, char (primitive types) Resultant type is boolean and has value true or false Has lower precedence than the arithmetic operators, >= has higher precedence than == and !=

GP4, Martin Lillholm 12 Boolean Expressions using Relational Operators Examples ( x=2 and y=4 ): ExpressionValue false true true == falsefalse x != ytrue x < 3 + ytrue y < x + 3true (x + y > 3) == falsefalse false != x < 3true x == y == falsetrue

GP4, Martin Lillholm 13 Logical Operators OperatorMeaningEksempel ! Not (unary) !(x == 60) && And (binary) 0<= x && x <= 60 || Or (binary) x =60 Both argument and resultant type is boolean ! has higher precedence than && which has higher precedence than || ! has higher precedence than both the relational and arithmetic operators && and || has lower precedence than both the relational and arithmetic operators If expr1 is false in expr1 && expr2 then expr2 isn’t evaluated If expr1 is true in expr1 || expr2 then expr2 isn’t evaluated

GP4, Martin Lillholm 14 Logical Operators, Truth Tables x!x truefalse true xyx && yx || y false truefalsetrue false true

GP4, Martin Lillholm 15 Examples ( x=2 and y=4 ): Boolean Expressions with Logical Operators UdtrykVærdi !falsetrue !truefalse !true == falsetrue !(true == false)true true && falsefalse false || truetrue (x + y > 3) && x < ytrue x + y == 3 || x < 4true x < y && (3*4 == 2*6-1*2+2) == !(3<x)true

GP4, Martin Lillholm 16 The if Statement Used for affecting flow of control based on boolean expressions And is thus used to make choices based on data: –Is one number bigger than another? –Is a number within a certain interval or outside? –Are two String s identical? Is typically used when we need to: –React to data - unknown at compile time –Entered numbers, strings etc. –Data stored in files –Random numbers –... condition S statement(s) true false

GP4, Martin Lillholm 17 The if statement – Syntax if ( expr ) statement; if is a reserved word expr has to be boolean and thus evaluate to either true or false If expr evaluates to true, statement is executed and otherwise skipped

GP4, Martin Lillholm 18 The if Statement – Examples int a=5; if (a > 10) a = a – 5; System.out.println(”a is: ” + a); if (a>0 && a <=10) System.out.println(”a is in the interval from 1 to 10”); if (a 10) System.out.println(”a isn’t in the interval from 1 to 10”); if (a == 5) a = 3; if (a != 5) a = 5; if (a 10000) System.out.println(”a is negative or very large”);

GP4, Martin Lillholm 19 The if Statement – Example Limitations ? Either or... Several statements in the true branch

GP4, Martin Lillholm 20 The if-else Statement Syntax if (expr) statement1; else statement2; Examples: if (level > MAX) System.out.println(”Level Critical!”); else System.out.printlnt(”Level ok”); if (a > b -.01 && a < b +.01) a = b; else System.out.println(”a is different from b”); condition statement1 truefalse statement2

GP4, Martin Lillholm 21 The if-else – Example

GP4, Martin Lillholm 22 if-else – Example

GP4, Martin Lillholm 23 Block Statements if (a > b) // swap a and b tmp = a; a = b; b = tmp; else a = a + 1; if (a > b) { // swap a and b tmp = a; a = b; b = tmp; } else a = a + 1; {... } is used to combine statements in blocks as we do in classes, constructor, and methods. A block statement can always substitute any single statement. Indentation doesn’t mean anything – logically speaking – but makes the program a lot more readable

GP4, Martin Lillholm 24 Block Statements - Example

GP4, Martin Lillholm 25 Nested if Statements – Example

GP4, Martin Lillholm 26 Nested if Statements – A Pitfall … if (b < 0) if (a < b) System.out.println(”Både a og b er negative”); else System.out.println(”b er negativ”); if (b < 0) { if (a < b) System.out.println(”Både a og b er negative”); } else System.out.println(”b er negativ”); else always “belongs” to closest unmatched if – bar {} ’s

GP4, Martin Lillholm 27 Comparing Data Some primitive types ( integer, long, short, byte ) are compared as we seen so far. Decimal type ( float, double ) are still approximations and always be compared within and certain tolerance and not using e.g == final double TOLERANCE = ; if (Math.abs(f1-f2) < TOLERANCE) System.out.println(”f1 and f2 are approx. equal”); Characters char is compared using their Unicode: ’0’.. ’9’ < ’A’.. ’Z’ < ’a’... ’ z’ ‘A’ != ‘a’

GP4, Martin Lillholm 28 Comparing Data ( String ) Think of strings as a sequence of characters (from left to right). This gives an ordering (lexicographic ordering). “garden” before “gardens” and “Martin” before “anders” Vi cannot use e.g. == and <= directly – see next slide equals and compareTo methods I the String class if (name1.equals(name2)) System.out.println (”The names are the same”); else System.out.println (”The names are not the same”); int result = name1.compareTo(name2); if (result < 0) System.out.println(name1 + ” comes before ” + name2); else if (result == 0) System.out.println (”The name are the same”); else System.out.println (name1 + ” follows ” + name2);

GP4, Martin Lillholm 29 Comparing Data (Objects) We’ll return to object comparison in general. But == applied to objects compares references.

GP4, Martin Lillholm 30 The switch Statement Alternative construction to select one or more of several statements Based on an integral expression one or more options from a given list is selected – possibly the default option is none matches. Program execution continues a the option that matches the expression option switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: System.out.println(”No match”); }

GP4, Martin Lillholm 31 The switch Statement The purpose af break The purpose of default Implicit blocks The expression must be an integral type: ( int, char or (enumerated type)) The cases must be literals Equivalent to a series of if statements but sometimes more elegant

GP4, Martin Lillholm 32 switch – Example

GP4, Martin Lillholm 33 while Loops Repeats a statement or block 0 or more times while (expr) statement; If expr evaluates to true, statement is executed expr is evaluated again and if true, statement is executed again … Continues until expr evaluates to false int count = 1; while (count <= 5) { Sytem.out.println (count); count++; } Boolean expression statement true false condigtion

GP4, Martin Lillholm 34 while loops – Example

GP4, Martin Lillholm 35 while loops – Example

GP4, Martin Lillholm 36 Infinite Loops int count = 1; while (count <= 25) { System.out.println (count); count = count - 1; } while (true) { System.out.println (”This will take a while...”); } int j = 0; while (j < 10) { j = j + 0; System.out.println(j); } double num = 1.0; while (num != 0.0) num = num – 0.1;

GP4, Martin Lillholm 37 Nested Loops int count1, count2; count1 = 1; while (count1 <= 10) { count2 = 1; while (count2 <= 50) { System.out.println(”Here again”); count2++; } count1++; }

GP4, Martin Lillholm 38 Nested Loops

GP4, Martin Lillholm 39 do loops Very similar to while loops except that the condition is evaluated after the body – thus do loops always run at least once do statement; while (expr) int count = 0; do { count++; System.out.println(count); } while (count < 5); true condition statement false Boolean expression

GP4, Martin Lillholm 40 do loops – Example

GP4, Martin Lillholm 41 for loops for ( initialisation ; condition ; increment ) statement; Initialisation Excuted once before the loop body statement is executed until condition evaluates to false “increment” executed after the loop body at the end of each iteration

GP4, Martin Lillholm 42 for loops statement true condition evaluated false increment initialization

GP4, Martin Lillholm 43 for loops - Examples int i; for (i=0; i<10; i++) System.out.println(”i:” + i); for (int j=1; j<10; j++) System.out.println(”j:” + j); for (i=9; i >= 0; i--) { k = i + 2; System.out.println(”k:” + k); } –L&L Multiples.java ( side 248 ) –L&L Stars.java ( side 250 )

GP4, Martin Lillholm 44 All Loops Constructs are Equivalent while do for

GP4, Martin Lillholm 45 Advise on Variable Declaration and Initialisation Declare variables as local as possible Declare variables close to their first use Declare loop variables close to or in the loop construct (only possible for for loops)

GP4, Martin Lillholm 46 Graphics using Loops –Bullseye.java og BullseyePanel.java i BlueJ (L&L page ) –Boxes.java (L&L page )