Flow Control in Java.

Slides:



Advertisements
Similar presentations
Flow of Control Chapter 3.
Advertisements

Chapter 7 - Iteration. Chapter Goals Program repitiation statements – or loops – with the for, while, and do-while statements Program repitiation statements.
Control Structures. Decision Making Structures The if and if…else are all selection control structures that introduce decision-making ability into a program.
Intro to CS – Honors I Control Flow: Loops GEORGIOS PORTOKALIDIS
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Repetition Statements Recitation – 02/20/2009 CS 180 Department of Computer Science, Purdue University.
Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Introduction to Java Programming, 4E Y. Daniel Liang.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
For Loops 1 Loops/Iteration Used to repeat an action Must have a STOP condition Three flavors - for, while, do/while Which loop to use? task with a specific.
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Chapter 5 Loops.
Using Shortcut Arithmetic Operators Accumulator: A variable that is used to total. Its value is repeatedly increased by some amount. Java provides shortcuts.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Flow Control in Java. Controlling which instruction to execute next Sequential  Similar to walking, one step after another Branching  Similar to a fork.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Repetition. Control of Flow SEQUENCE SELECTION (if..else, switch…case) REPETITION.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Java Prepared by Gary Langner Types of Loops u for loop (entrance controlled) –do an action for a definite number of times u while loop (entrance controlled.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
COMP Loop Statements Yi Hong May 21, 2015.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Catie Welsh February 9,  Friday - No Lab! ◦ Bring questions on Project 2  Lab 3 due on Friday 2.
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.
Loops ( while and for ) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan 1.
Topic : While, For, Do-While Loop Guided By : Branch : Batch :
Repetition Statements
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
Chapter 6 More Conditionals and Loops
Chapter 5: Control Structures II
Loop Structures.
Week 4 – Repetition Structures / Loops
Topic 5 for Loops -Arthur Schopenhauer
CiS 260: App Dev I Chapter 4: Control Structures II.
Lecture 07 More Repetition Richard Gesick.
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Chapter 6 More Conditionals and Loops
CSS161: Fundamentals of Computing
Outline Altering flow of control Boolean expressions
Module 4 Loops.
Lec 4: while loop and do-while loop
Faculty of Computer Science & Information System
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 14, 2011
Control Statements Loops.
Repetition Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Flow Control in Java

Controlling which instruction to execute next Sequential Similar to walking, one step after another Branching Similar to a fork in the road Depending on the destination, you choose one way or the other, not both Repetition Similar to running on a track in the Olympics Repeating the same track in a loop

Sequential x = 1; x = x + 1; As expected First instruction first Second instruction second What if we swap the two instructions? That is Instructions cannot be in arbitrary order

Branching (Conditional Statements) if ( x < y ) // boolean condition x = x + 1; // execute if true else y = y * 10; // execute if false

Second/Else Branch is Optional if ( x < y ) // boolean condition x = x + 1; // execute if true

Multiple Instructions in One Branch if ( x < y ) { // note the matching braces x = x + 1; y = y – x; } else { y = y * 10; x = y / x;

Nested Branching if ( x < y ) { x = x + 1; if ( y > 10) y = y – x; } else y = y * 10; x = y / x;

Cascaded Branching if (score >= 90) grade = ’A’; else if (score >= 80) grade = ’B’; else if (score >= 70) grade = ’C’; else if (score >= 60) grade = ’D’; else grade = ’F’;

Version 2: always correct answer? if (score >= 90) grade = ’A’; if (score >= 80) grade = ’B’; if (score >= 70) grade = ’C’; if (score >= 60) grade = ’D’; if (score < 60) grade = ’F’;

Version 3: always correct answer? if (score >= 90) grade = ’A’; if (score >= 80 && score < 90) grade = ’B’; if (score >= 70 && score < 80) grade = ’C’; if (score >= 60 && score < 70) grade = ’D’; if (score < 60) grade = ’F’;

Repetition (looping) for while do-while (“Repeat until”) “counting” loops frequently (sometimes inappropriately) used while general loops most flexible do-while (“Repeat until”) at least once least used

ICU Initialize (start) Continue (or stop) Update What is the initial/starting condition? Continue (or stop) When to continue/stop? In what condition does it continue/stop? Update How to update the condition? If ICU is not carefully designed (common mistake) your program will be in ICU

Counting loop – 1, 2, 3, … 10 for (int num = 1; num <= 10; num++) System.out.println(num); for (initialize; continue; update) body -- instruction(s) to be repeated Continue --boolean (continue if true, stop if false)

How about from 55 to 123? for (int num = ?; ?; ?) System.out.println(num);

How about from 55 to 123? for (int num = 55; num <= 123; num++) System.out.println(num);

How about 10 numbers from 55? for (int num = ?; ?; ?) System.out.println(num);

How about 10 numbers from 55? // version 1? for (int num = 55; num <= 64; num++) System.out.println(num); // version 2? for (int num = 55; num <= 65; num++) // version 3? for (int num = 55; num < 65; num++)

How about 10 even numbers from 2? for (int num = ?; ?; ?) System.out.println(num);

How about 10 even numbers from 2? // version 1? for (int num = 2; num <= 20; num=num+2) System.out.println(num); // version 2? for (int num = 2; num <= 18; num=num+2) // version 3? for (int num = 2; num < 20; num=num+2)

How about 10 even numbers down from 100? for (int num= ? ; ?; ?) System.out.println(num);

How about 10 even numbers down from 100? // version 1? for (int num=100; num >= 80; num=num-2) System.out.println(num); // version 2? for (int num=100; num >= 82; num=num-2) // version 3? for (int num=100; num > 82; num=num-2)

Anything that is strange? for (int num=10; num < 10; num++) System.out.println(num);

Anything that is strange? for (int num=10; num < 10; num++) System.out.println(num); continue is never true, body never executes

Anything that is strange? for (int num=10; num >= 10; num++) System.out.println(num);

Anything that is strange? for (int num=10; num >= 10; num++) System.out.println(num); Continue is always true, infinite loop (eventually stops since int has an upper limit and num overflows)

Finding Sum of 1 to 10 int sum = 0; for (int num = 1; num <= 10; num++) sum = sum + num;

Finding Sum of 1 to 10 int sum = 0; for (int num = 1; num <= 10; num++) sum = sum + num; // --- version 2 ? --- for (int num = 1; num < 10; num++)

Sum of first 10 even numbers int sum = 0; for (int num = ?; ? ; ?) sum = sum + num;

Sum of first 10 even numbers int sum = 0; for (int num = 0; num <= 18; num = num + 2) sum = sum + num;

Printing a Line of 5 Stars for (int star = 1; star <= 5; star++) { System.out.print(’*’); } System.out.println(); // new line // --- output: --- *****

Printing a Line of 5 Stars for (int star = 1; star <= 5; star++) { System.out.print(’*’); } System.out.println(); // new line // --- version 2 ? --- for (int star = 0; star < 5; star++)

4x5 Rectangle of Stars ?? for (int star = 1; star <= 5; star++)//5 stars { System.out.print(’*’); } System.out.println(); // --- Output: --- *****

4x5 Rectangle of Stars – nested loop for (int line = 1; line <= 4; line++) //4 lines { for (int star = 1; star <= 5; star++)//5 stars System.out.print(’*’); } System.out.println(); // --- Output: --- *****

Triangle of Stars * ** *** **** *****

“While” loop int num = 1, sum = 0; while (num <= 10) { sum = sum + num; num++; } initialize while (continue) // repeat if continue is true update

A program with an exit command boolean exit = false; while (exit == false) { // do stuff if ( //exit command is entered ) exit = true; }

Is num a prime number?

Is num a prime number? Definition Only divisible by 1 or itself Check divisors between 2 and num – 1 to see if num is divisible by divisor Don’t need to check divisors larger than num

Checking different divisors Initialize Start divisor with 2 Continue Divisor is less than num and num is not divisible by divisor Update Increment divisor

Checking different divisors // I: start divisor with 2 int divisor = 2; // C: divisor less than num and // num not divisible by divisor while (divisor < num && num % divisor != 0) { divisor++; // U: increment factor }

Print the answer as well // I: start divisor with 2 int divisor = 2; // C: divisor less than num and // num not divisible by divisor while (divisor < num && num % divisor != 0) { divisor++; // U: increment factor } System.out.println(?);

Print the answer as well // I: start divisor with 2 int divisor = 2; // C: divisor less than num and // num not divisible by divisor while (divisor < num && num % divisor != 0) { divisor++; // U: increment factor } if (divisor == num)//not divisible by smaller divisors System.out.println(“prime”); else System.out.println(“not prime”);

Which do you prefer? int divisor = 2; while (divisor < num && num % divisor != 0) { divisor++; } if (divisor == num) System.out.println(“prime”); else System.out.println(“not prime”); int divisor = 2; boolean prime = true; while (divisor < num) { if (num % divisor == 0) prime = false; divisor++; } if (prime == true) System.out.println(“prime”); else System.out.println(“not prime”);

“Do-While” loop Execute the loop body at least once continue is checked after the loop body is executed initialize do { update } while (continue); // repeat if continue is true // note the semicolon at the end

Checking input int numTickets = 0; do { System.out.print(”Please enter # of tickets: ”); numtickets = keyboard.nextInt(); } while (numTickets <= 0);

Checking Password String username = ””, password = ””; do { System.out.print(”Please enter username: ”); username = keyboard.next(); System.out.print(”Please enter password: ”); password = keyboard.next(); } while (!valid(username, password));

How to add at most 3 Trials? String username = ””, password = ””; do { System.out.print(”Please enter username: ”); username = keyboard.next(); System.out.print(”Please enter password: ”); password = keyboard.next(); } while (!valid(username, password));

At most 3 Trials String username = ””, password = ””; int trials=0; do { System.out.print(”Please enter username: ”); username = keyboard.next(); System.out.print(”Please enter password: ”); password = keyboard.next(); trials++; } while (!valid(username, password) && trials < 3);