Control Statements Loops

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

CS 117 Fall Compound boolean expressions. Control Statements, Part 2. Using boolean operators. Boolean operators

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Repetition Structures

More Programming Constructs -- Introduction

CS1004: Intro to CS in Java, Spring 2005

CompSci 125 Lecture 11

Repetition, Looping CS101

Controls Structure for Repetition

Topics. Chapter 5. Equality Operators

Chapter 4: Control structures. Repetition

Iteration statements - Loops

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

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Control structures

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

Computer Programming I - Unit 5 Lecture page 1 of 14

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Handout 4 Conditionals. Boolean Expressions.

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Introduction. C provides two styles of flow control:

Control Structures in Java if-else and switch

Repetition CSC 121 Fall 2014 Howard Rosenthal

Chapter Goals. Contents LOOPS

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition, Looping. While Loop

Loops / Repetition Statements

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

Review for Test 1 (Chapter 1-5)

Conditionals and Loops

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

CSCE 145 Exam 1 Review. This exam totals to 100 points. Follow the instructions. Good luck!

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

CSCE 145 Exam 1 Review Answers. This exam totals to 100 points. Follow the instructions. Good luck!

Building Java Programs

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

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

Introduction to Computing Lecture 07: Repetition and Loop Statements (Part II)

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

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

Loops (while and for)

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

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

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

CS1150 Principles of Computer Science Loops (Part II)

Logic & program control part 2: Simple selection structures

Example: Monte Carlo Simulation 1

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

Chapter 3. Selections

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

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Logical Operators and switch

Lecture 8 CSE11 Fall 2013 While Loops, Switch Statement, Simplifying Conditionals

ECE 122. Engineering Problem Solving with Java

Condition Controlled Loops. Introduction to Programming - Python

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

STUDENT LESSON A12 Iterations

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

CSCE 206: Structured Programming in C++

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

Control Structures II. Repetition (Loops)

CS112 Lecture: Repetition Statements

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

A Balanced Introduction to Computer Science, 3/E

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Midterm Examination (MTA)

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Introduction to Programming

5. Selection: If and Switch Controls

CS 112 Introduction to Programming

Accelerating Information Technology Innovation

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

CSCD 255 HW 2. No string (char arrays) or any other kinds of array variables are allowed

Flow of Control. Chapter 3. Chapter 3 1

Information Science 1

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

3chapter C ONTROL S TATEMENTS. Objectives

CHAPTER 5 FLOW OF CONTROL

Full file at

CS302: Self Check Quiz 2

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

About This Lecture. Repetition Control Structures - while. Outline. Repetition

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

Stepwise Refinement. Lecture 12 COP 3014 Spring February 2, 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

(Refer Slide Time: 00:26)

Increment and the While. Class 15

Repetition Algorithms

Condition Controlled Loops. Introduction to Programming - Python

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Control Structures in Java if-else and switch

Transcription:

CS 117 Spring 2004 Nested if statements if-else statements can reside within other if-else statements nested if statements Control Statements Loops April 26, 2004 Example (pseudocode) Get interest rate from the user. If interest rate is less than zero or greater than 100, print an error message. Else, if interest rate is greater than 1, divide interest rate by 100.0; calculate the new balance. Print out the account's balance. Interest rate (in Java code) String ratestr = JOptionPane.showInputDialog(null, Enter interest rate: ); double rate = Double.parseDouble(rateStr); if (rate > 100 rate < 0) { System.out.println( Invalid interest rate entered. ); else { if (rate > 1) { rate = rate/100.0;...

Comparing objects When we compare two numbers, we use the equality (==) operator if (a == b) equality for primitive types means the values are equivalent Equality for objects means at the same location in memory cannot use the == operator Example: comparing Strings The String class has an equals method and an equalsignorecase method Example: String s1 = this is a string ; String s2 = This is a STRING ; if (s1.equals(s2)) { System.out.println( match ); else if (s1.equalsignorecase(s2)) { System.out.println( match, ignoring case ); else { System.out.println( no match ); Comparing two objects If we want to compare two objects (Canvases, Accounts, etc), the class has to contain an equals method this method defines what constitutes equality for this class Example: Compare 2 Canvas objects 2 Canvas objects are equal if they have the same title and the same dimensions. switch statement Sometimes using if statements can be cumbersome conditions involve integer or character values, for example

Example String numstr = JOptionPane.showInputDialog(null, Enter your choice (1-5): ); int num = Integer.parseInt(numStr); if (num == 1) System.out.println( Do a headstand. ); else if (num == 2) System.out.println( Pat your head and rub your tummy. ); else if (num == 3) System.out.println( Do 3 jumping jacks. ); else if (num == 4) System.out.println( Recite a limerick. ); else if (num == 5) else System.out.println( Count backwards from 100 by 7's. ); System.out.println( You cannot follow directions, butthead! ); switch statement Replacement for if statements when the boolean expression involves testing an integer (int) or a character (char) also: byte, short Examples of integer tests: num (from previous example) 25 % 3 a / 3 (if a is an integer!) Example (revised) String numstr = JOptionPane.showInputDialog(null, Enter your choice (1-5): ); int num = Integer.parseInt(numStr); switch (num) { case 1: System.out.println( Do a headstand. ); case 2: System.out.println( Pat your head and rub your tummy. ); case 3: System.out.println( Do 3 jumping jacks. ); case 4: System.out.println( Recite a limerick. ); case 5: System.out.println( Count backwards from 100 by 7's. ); default: System.out.println( You cannot follow directions, butthead! ); Format of a switch statement switch (<expression>) { case <constant 1>: <statements> case <constant 2>: <statements>... case <constant n>: <statements> default: <statements>

Notes The <constant i> values must be constants integers/chars/bytes or defined constants of these types Cases can be in any order typically, default goes last break is used to make sure we only execute one of the statement blocks default clause is optional handles unexpected input or program behavior good programming practice Another example String choice = JOptionPane.showInputDialog(null, Enter a number between 1 and 7 ); int num = Integer.parseInt(choice); switch (num) { case 1: case 2: case 3: case 5: case 7: System.out.println( Prime number. ); case 4: System.out.println( Factors are 1, 2, and 4. ); case 6: System.out.println( Factors are 1, 2, 3, and 6. ); default: System.out.println( Invalid number entered. ); Control statement gotchas Not using breaks in your switch statements Using values that are not integers, chars, or bytes when using switch Making your if statements too complex simplify your logic! Using && when you mean to use and vice versa Using = (assignment) when you mean to use == (equality) Using == (equality) to compare objects Repetition statements Control statements allow us to execute certain blocks of code when certain conditions are met Repetition statements allow us to execute certain blocks of code more than once until some condition is met a set number of times Strings: equals() or equalsignorecase() should be used instead

Uses of repetition Game: allow the user to keep playing until he/she decides to quit Keep prompting the user for input until the user enters valid input Mathematical calculations average sum And many more! while do-while for Repetition statements while statement While some condition is true, do the following... pre-test loop: test the condition first, then execute the loop Example: int sum = 0, count = 1, maxsum = 500; while (sum < maxsum) { sum = sum + count; count = count + 2; System.out.println( Sum = +sum); Another example: valid user input String ratestr = JOptionPane.showInputDialog(null, Enter an interest rate: ); rate = Double.parseDouble(rateStr); while (rate < 0 rate > 100) {... ratestr = JOptionPane.showInputDialog(null, You entered an invalid rate. Please enter a rate between 0 and 100: ); rate = Double.parseDouble(rateStr);

Another example String choice = JOptionPane.showInputDialog(null, Enter a positive number (or any negative number to quit): ); int num = Integer.parseInt(choice); int sum = 0, count = 0; while (num >= 0) { count++; sum = sum + num; choice = JOptionPane.showInputDialog(null, Enter a positive number (or any negative number to quit): ); num = Integer.parseInt(choice); double average = ((double)sum)/count; System.out.println( The average of the numbers is +average); Format of a while statement while (<condition>) { <statement> <condition> is a boolean statement changes each time through the loop As long as <condition> is true, the loop will execute <statement>: loop body Types of loops count-controlled: the while loop executes a certain number of times example: count = 0; while (count < 100) { count++; sentinel-controlled: the while loop executes until a variable becomes a certain value the interest rate and averaging examples are this type the variable of interest is the sentinel interest rate: rate between 0 and 100 averaging: negative number entered by the user Infinite loop Overflow Using real numbers Off-by-one Other logic mistakes Gotchas

Infinite loop Probably the most common error Occurs when <condition> is never met program has no stopping point loops forever Example: int sum = 0; while (sum < 100) { count = 0; sum = sum + count; Other examples of infinite loops int prod = 0; while (prod < 100) { prod = prod * 3; int count = 0; while (count!= 25) { count = count + 3;