John Hurley Cal State LA

Slides:



Advertisements
Similar presentations
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Advertisements

Additional control structures. The if-else statement The if-else statement chooses which of two statements to execute The if-else statement has the form:
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Chapter 5 Loops.
John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
Chapter 5: Control Structures II
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
Chapter 5: Loops Tarik Booker CS 201 California State University, Los Angeles.
Computer Programming -1-
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Slides by Evan Gallagher
CompSci 230 S Programming Techniques
Loops A loop is: Java provides three forms for explicit loops:
Lecture 4b Repeating With Loops
Chapter 4 Repetition Statements (loops)
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 5: Control Structures II
Loop Structures.
User input We’ve seen how to use the standard output buffer
Repetition-Counter control Loop
Java Programming: Guided Learning with Early Objects
Repetition-Sentinel,Flag Loop/Do_While
Chapter 4 – Control Structures Part 1
Lecture 07 More Repetition Richard Gesick.
TK1114 Computer Programming
Lecture 4B More Repetition Richard Gesick
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
MSIS 655 Advanced Business Applications Programming
Outline Altering flow of control Boolean expressions
Java Language Basics.
Iteration: Beyond the Basic PERFORM
3 Control Statements:.
Control Statements Loops.
Lec 4: while loop and do-while loop
Lab5 PROGRAMMING 1 Loop chapter4.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Suggested self-checks:
Control Statements Loops.
Repetition Statements
Based on slides created by Bjarne Stroustrup & Tony Gaddis
PROGRAM FLOWCHART Iteration Statements.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Additional control structures
Review of Previous Lesson
Loops CGS3416 Spring 2019 Lecture 7.
Validation We have covered one way to get user input, using Scanner to get it from the console We will soon cover at least one additional way to get.
Presentation transcript:

John Hurley Cal State LA CS 201 Lecture 5 John Hurley Cal State LA

Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) { //statements } executes the statements repeatedly as long as the value of x is not equal to 0 when it is tested, which is at the beginning of each run through the loop. Loops are one of the most important techniques in programming. Why is this?

For Loop for(int i = 0; i <10; i++) { } System.out.println(i); } Declares an integer variable named i i is a loop counter. Many programmers would actually name it something like “counter” to make this as clear as possible; this is a very good practice: for(int counter = 0; counter < 10; counter++){ } Initially i is set to 0 Tests whether i is less than 10 If so, prints the values of I, then increments i by 1 If not, continues to whatever is after the loop the statements between the backers are a block could contain any number of statements, all of which execute each time through the loop.

Count from 0 to 9 public class Count{ public static void main(String[] args) { for (int i = 0; i < 10; i++){ System.out.println(i); }

Endless Loop You might deliberately write an endless loop (presumably with some way to terminate it other than the loop test) Also, it turns out that there is no algorithm that can determine whether a loop will eventually terminate Accordingly, the compiler and JVM do not protect you from accidentally writing one At the command line, you can stop a program gone awry by hitting <ctrl> c or by just closing the window

More on While Loops A while loop will continue as long as the test is true. public class WhileDemo{ public static void main(String[] args){ int thisVar = 0; while(thisVar < 10) System.out.println(thisVar++); }

More on While Loops The test may use a variable that does something more sophisticated than counting the loop: public class WhileDemo{ public static void main(String[] args){ int thisVar = 0; while(thisVar < 10) { // get a value of thisVar from input System.out.println(thisVar); }

Running of the Bulls int runnerPosition = 400, bullPosition = 600; int runnerSpeed = 4, bullSpeed = 7; int currSecond = 0; while(bullPosition > runnerPosition && runnerPosition > 0){ int runnerLead = bullPosition - runnerPosition; System.out.println("At " + currSecond + " second(s), runner is " + runnerPosition + " meters from safety and bull is " + runnerLead + " meters behind him."); runnerPosition -= runnerSpeed; bullPosition -= bullSpeed; currSecond++; } if(runnerPosition <= 0) System.out.println("Runner reached safety!"); else System.out.println("Runner gored at " + runnerPosition + " meters from safety!");

Nested Loops One loop may be inside another one Inner loop will execute its full run for every iteration of the outer loop Inner loop may use variables controlled by the outer loop How many times does the statement in bold execute? public class NestedLoopDemo{ public static void main(String[] args){ for(int a = 1; a <= 10; a++){ for(int b = 1; b <= 10; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); } How would you do a multiplication table?

Nested Loops Consider a case in which, for each iteration of the outer loop, the inner loop executes the same number of times as the outer loop: public class NestedLoopDemo2{ public static void main(String[] args){ int count = 0; int n = 5; for(int a = 1; a <= n; a++){ for(int b = 1; b <= n; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } Inner loop System.out.println() executes n2 times

Math Operations Modulo operator % find the remainder after division, discard the quotient 10 % 1 = 0 10 % 5 = 0 10 % 4 = 2 10 % 3 = 1

Math Operations Modulo operations have many uses in programming. One is to create a sequence of unlimited length using a finite set of resources, by taking turns in round-robin fashion Example of modulo logic: Stooge0, Stooge1, and Stooge2 will share some number of slaps on the head. We can only slap one Stooge at a time. slapslapNum goes to Stoogei, where i = currSlapNum % 3 int stoogeNum = slapNum % 3;

Math Operations 1 2

Modulo Operations

Shortcuts Operator Example Equivalent += i += 8 i = i + 8 -= f -= 8.0 f = f - 8.0 *= i *= 8 i = i * 8 /= i /= 8 i = i / 8 %= i %= 8 i = i % 8

Increment and Decrement Operators Operator Name Description ++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment. var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1. --var predecrement The expression (--var) decrements var by 1 and evaluates to the new value in var after the decrement. var-- postdecrement The expression (var--) evaluates to the original value in var and decrements var by 1.

Increment and Decrement Operators public class Increments{ public static void main(String[] args){ int num = 0; System.out.println(num); System.out.println(num++); System.out.println(++num); } Outputs this sequence: 1 2

Increment and Decrement Operators public class Increments{ public static void main(String[] args){ for(int num = 0; num < 5; num++) System.out.println(num); } outputs this sequence: 1 2 3 4

Increment and Decrement Operators What will this one do? public class Increments{ public static void main(String[] args){ for(int num = 0; num < 5; ++num) System.out.println(num--); }

Do…While Similar to while loop, but with test at the end, not the beginning Always executes at least once int x = 0; while ( x > 0) {} will never execute do{ } while ( x > 0); will execute at least once

Do…While Similar to while loop, but with test at the end, not the beginning Always executes at least once int x = 0; while ( x > 0) {} will never execute do{ } while ( x > 0); will execute at least once

Validation We have covered one way to get user input, using Scanner to get it form the console We will soon cover at least one additional way to get input We have noted that users are human beings and accordingly are impossible to predict Input is not always usable

Validation Screen input for problems before using it while and do… while loops are very handy for this Example: Scanner sc = new Scanner(System.in); int age; do { System.out.println("How old are you?"); age = sc.nextInt(); } while (age < 0 || age > 100); System.out.println("You entered " + age);

Validation We could still easily make the program above break enter “a” enter <esc> We will come back to validation soon