CSC 204 Programming I Loop I The while statement.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Repetition Statements Perform the same task repeatedly Allow the computer to do the tedious, boring things.
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter4: Control Statements Part I.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-2: The for Loop reading: 2.3 self-check: exercises: 2-14 videos:
CS150 Introduction to Computer Science 1
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
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.
Looping Yong Choi School of Business CSU, Bakersfield.
CS305j Introduction to Computing While Loops 1 Topic 15 Indefinite Loops - While Loops "If you cannot grok [understand] the overall structure of a program.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
JAVA Control Structures: Repetition. Objectives Be able to use a loop to implement a repetitive algorithm Practice, Practice, Practice... Reinforce the.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Chapter 6 Iteration.  Executes a block of code repeatedly  A condition controls how often the loop is executed while (condition) statement  Most commonly,
Chapter 6: Iteration Part 1. To be able to program loops with the while, for, and do statements To avoid infinite loops and off-by-one errors To understand.
CONTROLLING PROGRAM FLOW
Boolean expressions, part 2: Logical operators. Previously discussed Recall that there are 2 types of operators that return a boolean result (true or.
CSE 201 – Elementary Computer Programming 1 Extra Exercises Source: Suggested but not selected midterm questions.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
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.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Review TEST 2 Chapters 4,5,7. QUESTION For which type of operands does the == operator always work correctly: (a) int, (b) double, or (c) String?
Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic.
Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic.
Java Review if Online Time For loop Quiz on Thursday.
The for loop.
Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING While Loop.
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.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Structured Programming Structured Programming is writing a program in terms of only 3 basic control structures: sequence selection repetition We have already.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 4: Basic Control Structures Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 4 Basic.
Basic Control Structures
CompSci 230 S Programming Techniques
Week of 12/12/16 Test Review.
Lecture 7: Repeating a Known Number of Times
Control Structures.
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Repetition-Sentinel,Flag Loop/Do_While
Operators Laboratory /11/16.
OPERATORS (2) CSC 111.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Outline Boolean Expressions The if Statement Comparing Data
Basic Control Structures
Data types, assignment statements, and math functions allow you to compute You write a sequence of statements that tell the computer what needs to be done.
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Introduction to Computer Science I.
Review of Previous Lesson
Conditionals and Loops
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Control Statements:.
Presentation transcript:

CSC 204 Programming I Loop I The while statement

Recap: the if statement  Locate error below if (hour < 12); System.out.println(“AM”); else System.out.println(“PM”); if (hour >= 7 && hour <= 10) System.out.println(“Breakfast is served”); else (hour >= 11 && hour <= 13) System.out.println(“Lunch is served”);

Recap: the if statement  Examine the following code snippet i = -1; j = -2; if (i >= 0) if (j < 0) System.out.println(“j is negative”); else System.out.println(“i is negative”);

Program: Flipping a Coin CoinFlip2.java // Asks the user to guess a coin flip import jpb.*; public class CoinFlip2 { public static void main(String[] args) { boolean headsWasSelected = false; // Prompt user to guess heads or tails SimpleIO.prompt("Enter heads or tails: "); String userInput = SimpleIO.readLine(); if (userInput.equalsIgnoreCase("heads")) headsWasSelected = true; else if (!userInput.equalsIgnoreCase("tails")) { System.out.println("Sorry, you didn't enter heads " + "or tails; please try again."); return; }

Program: Flipping a Coin // Choose a random number double randomNumber = Math.random(); // Determine whether user guessed correctly if (headsWasSelected && randomNumber < 0.5) System.out.println("You win!"); else if (!headsWasSelected && randomNumber >= 0.5) System.out.println("You win!"); else System.out.println("Sorry, you lose."); }

The while Statement  When a while statement is executed, the controlling expression is evaluated first. If it has the value true, the loop body is executed and the expression is tested again.  Flow of control within a while statement:

A “Countdown” Loop  Consider the problem of writing a loop that displays a countdown: T minus 10 and counting T minus 9 and counting T minus 8 and counting T minus 7 and counting T minus 6 and counting T minus 5 and counting T minus 4 and counting T minus 3 and counting T minus 2 and counting T minus 1 and counting

A “Countdown” Loop  The countdown loop will need a counter that's assigned the values 10, 9, …, 1: int i = 10; while (i > 0) { System.out.println("T minus " + i + " and counting"); i -= 1; }  i != 0 could be used instead of i > 0 as the controlling expression. However, i > 0 is more descriptive, since it suggests that i is decreasing.

Counting Up  A loop that displays the numbers from 1 to n along with their squares: int i = 1; while (i <= n) { System.out.println(i + " " + i * i); i += 1; }  Output of the loop if n is 5:

Increment and Decrement Operators  Most loops that have a counter variable will either increment the variable (add 1 to it) or decrement the variable (subtract 1 from it).  One way to increment or decrement a variable is to use the + or - operator in conjunction with assignment: i = i + 1; // Increment i i = i - 1; // Decrement i  Another way is to use the += and -= operators: i += 1; // Increment i i -= 1; // Decrement i

Increment and Decrement Operators  Java has a special operator for incrementing a variable: ++, the increment operator.  There are two ways to use ++ to increment a variable: ++i; i++;  When placed before the variable to be incremented, ++ is a prefix operator.  When placed after the variable, ++ is a postfix operator.

Increment and Decrement Operators  Java also has an operator for decrementing a variable: --, the decrement operator.  The -- operator can go in front of the variable or after the variable: --i; i--;

Increment and Decrement Operators  When ++ and -- are used in isolation, it doesn’t matter whether the operator goes before or after the variable.  When ++ and -- are used within some other type of statement, it usually does make a difference: System.out.println(++i); // Increments i and then prints the new // value of i System.out.println(i++); // Prints the old value of i and then // increments i

Program: Counting Coin Flips  The CountFlips program will flip an imaginary coin any number of times.  After the user enters the number of flips desired, CountFlips will print the number of heads and the number of tails: Enter number of flips: 10 Number of heads: 6 Number of tails: 4

A Coin-Flipping Loop  There are several ways to write a loop that flips a coin n times.  Two possibilities: Technique 1 Technique 2 int i = 1; while (i 0) { … i++; n--;}  The first technique preserves the value of n. The second avoids using an additional variable.

CountFlips.java public class CountFlips { public static void main(String[] args) { // Prompt user to enter number of flips SimpleIO.prompt("Enter number of flips: "); String userInput = SimpleIO.readLine(); int flips = Integer.parseInt(userInput); // Flip coin for specified number of times int heads = 0, tails = 0; while (flips > 0) { if (Math.random() < 0.5) heads++; else tails++; flips--; } // Display number of heads and tails System.out.println("Number of heads: " + heads); System.out.println("Number of tails: " + tails); }

A Possible Modification  An alternate version of the while loop: while (flips-- > 0) if (Math.random() < 0.5) heads++; else tails++;

Ex public class Ex4_17 { public static void main(String[] args) { int n = 40; while (n > 0) { if (n % 2 == 0) n /= 2; else n = 3 * n + 1; System.out.print(n + " "); }

Recap: the if statement  Show values in i and j i = 5; j = --i + 1; i = 5; j = i++ - 1; i = 1; j =2 * ++i; i = 1; j =2 * i--;