# Introduction to Computer Programming

Size: px
Start display at page:

## Transcription

1 Introduction to Computer Programming Lecture #7 - Conditional Loops The Problem with Counting Loops Many jobs involving the computer require repetition, and that this can be implemented using loops. Counting loops allows us to perform a statement or a block of statements a certain number of times. The problem is that we do not always know exactly how many times to perform the statements in a loop in every situation.

2 The Problem with Counting Loops (continued) Let s take another look at our payroll program: We do not always know how payroll records that we have. It isn t very convenient to have to count the records, especially if it s a big number. Wouldn t it be better if we could keep going until we enter some special value to tell the computer to stop? Conditional Loops Conditional loops allow us to do this. Conditional loops keep repeating as long as some condition is true (or until some condition becomes true). Steps in solving a problem that involve while, until, as long as indicate a conditional loop.

3 While Loops The most common form of conditional loops are while loops. In Java, they have the form: while (condition) statement; or while(condition) { statements A simple example - KeepAsking import java.util.scanner; public class PickPositive { // A simple example of how while works public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int number; //Get your first number ("Hi there. Pick a positive integer"); number = keyb.nextint();

4 //Keep reading number as long as they are // positive while (number > 0) { ("Pick another positive integer"); number = keyb.nextint(); (number + " is not a positive integer"); The test average program revisited Let s take another look at our program to calculate test average: Write a program that can calculate a test average and grade for any number of tests. The program will finish when the user types in a grade of -1.

5 Sentinel Value Often conditional loops continue until some special value is encountered in the input which effectively tells the program to stop running the loop. This is called a sentinel value because it is the value for which we are watching. -1 is the sentinel value in the GPA algorithm s main loop The TestAverage Algorithm 1. As long as there are more grades, add them to the total 2. Divide the total by the number of courses 3. Print the corresponding letter grade

12 Payroll program revisited Let s revisit the payroll program. Instead of counting up the payroll records so we can count the number of times we go through the loop, why not use some sentinel value in the last entry to tell the program when we re finished? Since no one will ever make \$0.00 per hour, we ll use a pay rate of 0 as our sentinel value in the revised payroll program. Our Initial Payroll Algorithm 1. Display instructions for the user 2. Keep processing payroll records as long as there are more.

13 Refining the Payroll Algorithm 1. Display instructions for the user 2. Keep processing payroll records as long as there are more. 2.1 Get the first pay rate 2.2 while The Rate is positive: 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate 2.2 while The Rate is positive: 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count while (rate > 0.0) {

14 Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate 2.2 while (rate > 0.0) { 2.3 Process payroll record 2.4 Get the next pay rate 2.5 Print final count Calculate gross pay Print gross pay Increment record count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { Calculate gross pay Print gross pay Increment record count 2.4 Get the next pay rate 2.5 Print final count Get hours worked Calculate gross pay

15 Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { Get hours worked Calculate gross pay Print gross pay Increment record count 2.4 Get the next pay rate 2.5 Print final count "Enter the hours worked?"); hours = keyb.nextint(); Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); Calculate gross pay Print gross pay Increment record count 2.4 Get the next pay rate 2.5 Print final count if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours;

16 Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; Print gross pay Increment record count 2.4 Get the next pay rate System.out.printf ("Gross pay is \$%4.2f\n\n", pay); Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; System.out.printf ("Gross pay is \$%4.2f\n\n", pay); Increment record count 2.4 Get the next pay rate numpeople++;

17 Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { ("Enter the hours worked?"); hours = keyb.nextint(); if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours; System.out.printf ("Gross pay is \$%4.2f\n\n", pay); numpeople++; ("What is the pay rate for the " + "next employee? "); rate =keyb.nextdouble(); 2.5 Print the final count Refining the Payroll Algorithm 1. Display instructions for the user 2.1 Get the first pay rate while (rate > 0.0) { 2.5 Print the final count ("To stop the program, enter a pay rate" + " of zero or less \n\n");

18 Refining the Payroll Algorithm ("To stop the program, enter a pay rate" + " of zero or less \n\n"); 2.1 Get the first pay rate while (rate > 0.0) { 2.5 Print the final count ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); Refining the Payroll Algorithm ("To stop the program, enter a pay rate" + " of zero or less \n\n"); ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); while (rate > 0.0) { 2.5 Print the final count ("There were " + numpeople + " payroll records.");

19 import java.util.scanner; The Payroll Program public class Payroll2 { // Processes a payroll for a given number of // employees. The user indicates that (s)he is // finished by entering a pay rate that is zero // or negative. public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int numpeople = 0; double hours, rate, pay; // Display instructions ("To stop the program, enter a pay rate" + " of zero or less \n\n"); // Ask the user for the first employee s // pay rate ("What is rate of pay for the employee? "); rate = keyb.nextdouble(); // Calculate gross salary for everyone on the // payroll while (rate > 0.0) { // Enter the hours worked ("Enter the hours worked?"); hours = keyb.nextint(); // Calculate and print the pay. // If hours exceed 40, pay time and a half if (hours > 40) pay = 40*rate + 1.5*rate*(hours-40); else pay = rate * hours;

20 System.out.printf ("Gross pay is \$%4.2f\n\n", pay); numpeople++; // Get the pay rate for the next employee ("What is the pay rate for the " + "next employee? "); rate =keyb.nextdouble(); ("There were " + numpeople + " payroll records."); ("Payroll is finished."); Compound Interest program revisited Our earlier program showed how much interest is compounded over a given number of years. Let s see how long your money would have to earn interest to reach a million dollars

21 Redesigning Our Compound Interest Program Input Input deposit Output The final year and exact balance Other information New Principle = (1 + Interest Rate) * Old Principle Initial Algorithm: Set the initial principle at \$24 For every year since 1625, add 5% interest to the principle until the principle reaches \$1,000,000 and print the principle every twenty years and when it reaches \$1 million Print the values for the final year Refining The Compound Interest Algorithm 1. Set the initial principle at \$24 2. For every year since 1625, add 5% interest to the principle until the principle reaches \$1,000,000 and print the principle every twenty years and when it reaches \$1 million 3. Print the values for the final year 2.1 Set Year to While Principle < \$1,000, Add 5% Interest to the Principle 2.4 If the Year % 20 = then print the principle

22 Refining The Compound Interest Algorithm 1. Set the initial principle at \$ Set Year to While Principle < \$1,000, Add 5% Interest to the Principle 2.4 If the Year % 20 = then print the principle 3. Print the values for the final year while (principle < target) { Refining The Compound Interest Algorithm 1. Set the initial principle at \$ Set Year to 1625 while (principle < target) { 2.3 Add 5% Interest to the Principle 2.4 If the Year % 20 = then print the principle 3. Print the values for the final year interest = rate * principle; principle = principle + interest;

23 Refining The Compound Interest Algorithm 1. Set the initial principle at \$ Set Year to 1625 while (principle < target) { interest = rate * principle; principle = principle + interest; 2.4 If the Year % 20 = then print the principle 3. Print the values for the final year if (year%20 == 5) System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); Refining The Compound Interest Algorithm 1. Set the initial principle at \$ Set Year to 1625 while (principle < target) { interest = rate * principle; principle = principle + interest; if (year%20 == 5) System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year++; 3. Print the values for the final year System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle);

24 Refining The Compound Interest Algorithm 1. Set the initial principle at \$ Set Year to 1625 System.out.printf("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); principle = 24; Refining The Compound Interest Algorithm principle = 24; 2.1 Set Year to 1625 System.out.printf("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year = 1625;

25 The Revised Compound Interest Program import java.util.scanner; public class Interest4 { // Calculate the interest that the Canarsie Indians // could have accrued if they had deposited the \$24 // in an bank account at 5% interest. public static void main(string[] args) { int year = 1625; final double rate = 0.05, target = ; double interest, principle; // Set the initial principle at \$24 principle = 24; // For every year since 1625, add 5% interest // to the principle until the principle // reaches \$1,000,000 // Print the principle every twenty years // and when it reaches \$1 million // There has to be two fixed places for the // principle interest = 0; while (principle < target) { interest = rate * principle; principle = principle + interest; if (year%20 == 5) // Use 15 places for printing the principle System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); year++;

26 //Print the values for the final year System.out.printf ("year = %4d\tinterest = %13.2f" + "\tprinciple = %15.2f\n", year, interest, principle); Magic Number Problem The magic number game involves guessing a number and with each wrong guess, the player is told too high or too low. The goal is to guess the number in the smallest number of tries. We need a method for having the computer pick a number at random for the player to guess. We will need to learn about how to use library functions to provide us with the magic number.

27 Designing the Magic Number Algorithm Input The player s guess(es) Output A clue ( too high or too low ) and the number of guesses that it took. Initial Algorithm 1. Use the random number function to pick a number Let the player make a guess As long as the player hasn t guessed the number, give the appropriate clue and let him/her guess again. Print the number of tries Refining the Magic Number Algorithm Use the random number function to pick a number 2. Let the player make a guess 3. As long as the player hasn t guessed the number, give the appropriate clue and let him/her guess again. 4. Print the number of tries 3.1 While the guess isn t the magic number: 3.2 Give the appropriate clue 3.3 Increment the count of tries 3.4 Let the player make another guess.

28 Refining the Magic Number Algorithm 1. Use the random number function to pick a number 2. Let the player make a guess 3.1 While the guess isn t the magic number: 3.2 Give the appropriate clue 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries if the number is too high, say so Else say that the number is too low. Refining the Magic Number Algorithm 1. Use the random number function to pick a number 2. Let the player make a guess 3.1 While the guess isn t the magic number: If the number is too high, say so Else say that the number is too low. 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries while (guess!= magic) {

29 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { If the number is too high, say so Else say that the number is too low. 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic){ if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); 3.3 Increment the count of tries 3.4 Let the player make another guess. 4. Print the number of tries tries++;

30 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic){ if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; 3.4 Let the player make another guess. 4. Print the number of tries ("Guess?"); guess = keyb.nextint(); 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; ("Guess?"); guess = keyb.nextint(); 4. Print the number of tries ("You took " + tries + " guesses\n");

31 1. Use the random number function to pick a number 2. Let the player make a guess while (guess!= magic) { if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); tries++; ("Guess?"); guess = keyb.nextint(); ("** Right!! ** "); (magic + " is the magic number\n"); ("You took " + tries + " guesses\n"); ("Guess?"); guess = keyb.nextint(); import and Standard Classes (rand) It is frequently helpful to be able to use software routines that have already been written for common tasks. and keyb.nextint() are examples of this. import allows us to access entire libraries of routines that are part of one or more classes When we write: import java.util.scanner; We are telling the Java compiler where to find the definitions of the Scanner class.

32 import and Standard classes (Random) To use the random number function, we need to include import java.util.*; This tells the computer that java.util contains subdirectories with class definitions that it will need to use. A class is similar to a data type but it can be defined by a programmer or may come as a standard part of the programming language. Classes need to be initialized before use: Scanner keyb = new Scanner(System.in); The name of the random number function that we want is nextint() it is part of the object that we will declare called newrandomnumber. import java.util.*; The Magic Number Program public class MagicNumber { // The magic number game has the user trying to // guess which number between 1 and 100 the // computer has picked public static void main(string[] args) { Scanner keyb = new Scanner(System.in); Random newrandomnumber = new Random(); int magic, guess; int tries = 1; // Use the random number function to pick a // number magic = newrandomnumber.nextint(100) + 1;

33 // Let the user make a guess ("Guess?"); guess = keyb.nextint(); while (guess!= magic) { // Otherwise tell him whether it's too high // or too low else if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); // Let the user make another guess ("Guess?"); guess = keyb.nextint(); tries++; // If the user won, tell him/her ("** Right!! ** "); (magic + " is the magic number\n"); // Tell the user how many guesses it took ("You took " + tries + " guesses\n");

34 Declaring Boolean Constants If we want to work with true and false we can work with boolean variables. We can write: boolean married = true; if (married) ("The employee is married\n");! operator Sometimes we want to test to see if a condition is not true. We can do this by using the not operator, which is written as!: if (!married) ("Do you" + " want to bring a" + " date? ");

35 && and Operators Sometimes there may be two or more conditions to consider.for this reason we have the && (AND) and (OR) operators. If we declare boolean p, q; Both p and q must be true for p && q to be true. p q is true unless both p and q are false. do.. while loops You may have noticed that we asked the user twice for same information - the number (s)he is guessing. Some loops really require that the condition be at the end - not at the beginning. In Java, we have the do.. while loop, whose syntax is: do { statement(s) (condition)

36 Revisiting the magic number program The main loop in the magic number program becomes: do { ("Guess?"); guess = keyb.nextint(); // Otherwise tell him whether it's too high // or too low if (guess > magic) (".. Wrong.. Too high\n"); else (".. Wrong.. Too low\n"); // Try one more time tries++; while (guess!= magic);

37 Nim The game Nim starts out with seven sticks on the table. Each player takes turns picking up 1, 2 or 3 sticks and cannot pass. Whoever picks up the last stick loses (the other player wins). Input The Nim Problem The number of sticks the player is picking up Output The number of sticks on the table Who won (the player or the computer) Other Information Whoever leaves 5 sticks for the other player can always win if they make the right followup move: If the other player takes 1, you pick up 3 If the other player takes 2, you pick up 2 If the other player takes 3, you pick up 1

38 Designing The Nim Algorithm 1.Print the instructions 2.Set the number of stick at 7 and initialize other values 3.Find out if the user wants to go first or second 4.If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5.As long as there is no winner, keep playing 1. Print the instructions 2. Set the number of stick at 7 and initialize other values 3. Find out if the user wants to go first or second 4. If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5. As long as there is no winner, keep playing 5.1 While there is no winner 5.2 Find out how many sticks the user is taking 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner

39 1. Print the instructions 2. Set the number of stick at 7 and initialize other values 3. Find out if the user wants to go first or second 4. If the user goes second, have the computer take two sticks and the user goes second, have the computer take two sticks. 5.1While there is no winner 5.2 Find out how many sticks the user is taking 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner Make sure the user picked 1, 2, or 3 sticks Make sure that user didn t take more sticks than are on the table 5.1While there is no winner 5.2 Find out how many sticks the user is taking Make sure the user picked 1, 2, or 3 sticks Make sure that user didn t take more sticks than are on the table 5.3 Make sure it s a valid choice 5.4 Pick up the appropriate number of sticks. 5.5 Take the sticks off the table 5.6 See if there is a winner if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; else if (sticksleft == 4) reply = 3; else if (sticksleft == 3) reply = 2;

40 5.1While there is no winner if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; 5.5 Take the sticks off the table 5.6 See if there is a winner else if (sticksleft == 1) { ("Congratulations! You won!"); winner = true; else if (sticksleft == 0) { System.out..println(" Sorry, the computer has won " "- you have lost..."); winner = true; checking for valid input Very often, people will enter data that is not valid. An example of this is a negative number of hours worked, a name that contains numbers, a ten-digit zip code, etc. It is very important to learn how to check for bad data and what to do when you encounter it.

41 5.1While there is no winner Make sure it s a valid choice if (sticksleft == 6 sticksleft == 5 sticksleft ==2) reply = 1; else if (sticksleft == 0) { 5.5 Take the sticks off the table Make sure the user picked 1, 2, or 3 sticks Make sure that user didn t take more sticks than are on the table import java.util.scanner; The Nim Program public class Nim { // A program for the class game of Nim public static void main(string[] args) { Scanner keyb = new Scanner(System.in); int sticksleft, pickup, reply; boolean winner, move; char answer; String answerstring = new String(); // Print the instructions ("There are seven (7) sticks on the table."); ("Each player can pick up one, two, or " + "three sticks");

43 // If the user goes first, tell him how many // sticks are on the table else ("There are " + sticksleft + " on the table."); // As long as there is no winner, keep playing while (!winner) { move = false; // How many sticks is the user taking while (!move) { ("How many sticks do " + "you wish to pick up?"); pickup = keyb.nextint(); // Make sure its 1, 2 or 3 if (pickup < 1 pickup > 3) (pickup + " is not a legal number of sticks"); // Make sure that there are // enough sticks on the table else if (pickup > sticksleft) ("There are not " + pickup + " sticks on the table" ); else move = true; // Take the sticks off the table sticksleft = sticksleft - pickup;

44 // Plan the computer's next move if (sticksleft == 6 sticksleft == 5 sticksleft == 2) reply = 1; else if (sticksleft == 4) reply = 3; else if (sticksleft == 3) reply = 2; //See if the user won else if (sticksleft == 1) { ("Congratulations! You won!"); winner = true; // See if the user lost else if (sticksleft == 0) { ("Sorry, the computer has won " + "- you have lost..."); winner = true;

45 // If neither happened, get ready // for the next move if (!winner) { sticksleft = sticksleft - reply; ("The computer picked up " + reply + " sticks."); ("There are now " + sticksleft + " sticks left on the table.\n\n\n");

### Introduction to Computer Programming

Introduction to Computer Programming Lecture 3 Counting Loops Repetition with for Loops So far, repeating a statement is redundant: System.out.println("Homer says:"); System.out.println("I am so smart");

### Introduction to Computer Programming

Introduction to Computer Programming Lecture 2- Primitive Data and Stepwise Refinement Data Types Type - A category or set of data values. Constrains the operations that can be performed on data Many languages

### CSC 160 Introduction to Programming for Non-majors. Lecture 4 - Looping Around Loops I: Counting Loops. Why loops?

CSC 160 Introduction to Programming for Non-majors Lecture 4 - Looping Around Loops I: Counting Loops Why loops? Computers offer several advantages over calculators. If it is necessary, they can perform

### CSC 270 Survey of Programming Languages

CSC 270 Survey of Programming Languages C Lecture 1 : Getting Started: in C #include int { A First Program main(void) header makes input and output available to us printf("this is my first C

### CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

### Conditional Programming

COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,

### Controls Structure for Repetition

Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

### static String usersname; public static int numberofplayers; private static double velocity, time;

A class can include other things besides subroutines. In particular, it can also include variable declarations. Of course, you can declare variables inside subroutines. Those are called local variables.

### CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

### Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

### CS112 Lecture: Loops

CS112 Lecture: Loops Objectives: Last revised 3/11/08 1. To introduce some while loop patterns 2. To introduce and motivate the java do.. while loop 3. To review the general form of the java for loop.

### CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

These are sample pages from Kari Laitinen s book "A Natural Introduction to Computer Programming with Java". For more information, please visit http://www.naturalprogramming.com/javabook.html CHAPTER 5

### Chapter 3. Selections

Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### COMP 202 Java in one week

CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

### School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

### AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

### LOOPS. Repetition using the while statement

1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

### Programming with Java

Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

### 2.2 - Making Decisions

2.2 - Making Decisions So far we have only made programs that execute the statements in order, starting with the statements at the top of the screen and moving down. However, you can write programs that

### 4. Java Project Design, Input Methods

4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

### Introduction to Algorithms and Data Structures

Introduction to Algorithms and Data Structures Lecture 4 Structuring Data: Multidimensional Arrays, Arrays of Objects, and Objects Containing Arrays Grouping Data We don t buy individual eggs; we buy them

### Building Java Programs

Building Java Programs Chapter 4: Conditional Execution 1 loop techniques cumulative sum fencepost loops conditional execution Chapter outline the if statement and the if/else statement relational expressions

### COMP 110/L Lecture 4. Kyle Dewey

COMP 110/L Lecture 4 Kyle Dewey Outline New types: long and double Reading in with Scanner Performing operations on them How they interact with each other and other types Exponentiation with Math.pow()

### Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

### AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### 3 The L oop Control Structure

3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

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

Chapter 6 Repetition Statements Animated Version required for reproduction or display. Chapter 6-1 Objectives After you have read and studied this chapter, you should be able to Implement repetition control

### Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Building Java Programs Chapter 2: Primitive Data and Definite Loops Copyright 2008 2006 by Pearson Education 1 Lecture outline data concepts Primitive types: int, double, char (for now) Expressions: operators,

### ! 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

Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Introduction to Java Programs for Packet #4: Classes and Objects

Introduction to Java Programs for Packet #4: Classes and Objects Note. All of these programs involve writing and using more than one class file. 1. Copy the Box class and compile it. But you won t be able

### COMP 202. Java in one week

COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

### Java Coding 3. Over & over again!

Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

### The NetBeans IDE is a big file --- a minimum of around 30 MB. After you have downloaded the file, simply execute the file to install the software.

Introduction to Netbeans This document is a brief introduction to writing and compiling a program using the NetBeans Integrated Development Environment (IDE). An IDE is a program that automates and makes

### COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

### Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

### CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Introduction to Computer Science Unit 4B. Programs: Classes and Objects This section must be updated to work with repl.it 1. Copy the Box class and compile it. But you won t be able to run it because it

### Java I/O and Control Structures

Java I/O and Control Structures CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying

### Text Input and Conditionals

Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

### There are several files including the start of a unit test and the method stubs in MindNumber.java. Here is a preview of what you will do:

Project MindNumber Collaboration: Solo. Complete this project by yourself with optional help from section leaders. Do not work with anyone else, do not copy any code directly, do not copy code indirectly

### private static final char[] Alphabet = "abcdefghijklmnopqrstuvwxyz".tochararray();

//Shelley Latreille Hang Man Game /* This program plays the game Hang Man with the user. Hang Man is a game that requires the user to guess the letters of a word before running out of incorrect guesses.

### Building Java Programs

Building Java Programs Chapter 5 Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 The while loop while loop: Repeatedly executes its body as long as a logical test is true. while (test) { statement(s);

### CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

### Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

### Control Statements: Part 1

4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

### St. Edmund Preparatory High School Brooklyn, NY

AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

### CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

### Course Outline. Introduction to java

Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

### 1. An operation in which an overall value is computed incrementally, often using a loop.

Practice Exam 2 Part I: Vocabulary (10 points) Write the terms defined by the statements below. 1. An operation in which an overall value is computed incrementally, often using a loop. 2. The < (less than)

### Midterm Examination (MTA)

M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

### CSC 1051 Data Structures and Algorithms I

Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

### Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Object Oriented Programming. Java-Lecture 1

Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

### Computational Expression

Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name

### CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS Computers process information and usually they need to process masses of information. In previous chapters we have studied programs that contain a few variables

### Program Control Flow

Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

### Program Control Flow

Lecture slides for: Chapter 3 Program Control Flow Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

### AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal

Repe\$\$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative

### Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab

CSC 111 Fall 2005 Lab 6: Methods and Debugging Due Date: Two Program Demonstrations (Testing and Debugging): End of Lab Documented GameMethods file and Corrected HighLow game: Uploaded by midnight of lab

### STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

### Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal

Repe\$\$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

### Java I/O and Control Structures Algorithms in everyday life

Introduction Java I/O and Control Structures Algorithms in everyday life CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Source: http://xkcd.com/627/

### Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

### More on Classes. The job of this method is to return a String representation of the object. Here is the tostring method from the Time class:

More on Classes tostring One special method in Java is the tostring method. The method (regardless of which class it s added to) has the following prototype: public String tostring(); The job of this method

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

### Introduction to Computer Science Unit 3. Programs

Introduction to Computer Science Unit 3. Programs This section must be updated to work with repl.it Programs 1 to 4 require you to use the mod, %, operator. 1. Let the user enter an integer. Your program

### Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

### COMP 202 Java in one week

COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

### RANDOM NUMBER GAME PROJECT

Random Number Game RANDOM NUMBER GAME - Now it is time to put all your new knowledge to the test. You are going to build a random number game. - The game needs to generate a random number between 1 and

### Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

### The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

The for Loop, Accumulator Variables, Seninel Values, and The Random Class CS0007: Introduction to Computer Programming Review General Form of a switch statement: switch (SwitchExpression) { case CaseExpression1:

### COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015 Announcements Slides will be posted before the class. There might be few

### Lecture 8 " INPUT " Instructor: Craig Duckett

Lecture 8 " INPUT " Instructor: Craig Duckett Assignments Assignment 2 Due TONIGHT Lecture 8 Assignment 1 Revision due Lecture 10 Assignment 2 Revision Due Lecture 12 We'll Have a closer look at Assignment

### false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4 5 } 6 7 // Keywords: 8 byte, short, int, long, char, float, double, boolean, true, false, import, new Zheng-Liang Lu Java Programming 45

### Relational Operators EXAMPLE. C++ By

C++ By 9 EXAMPLE Relational Operators Sometimes you won t want every statement in your C++ program to execute every time the program runs. So far, every program in this book has executed from the top and

### Chapter 5: Control Structures

Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

### CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

### CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

### Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

### Building Java Programs

Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4 The if/else statement Executes one block if a test is true,

### Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do?

### CSCI 1301: Introduction to Computing and Programming Spring 2018 Project 3: Hangman 2.0 (A Word Guessing Game)

Introduction In this project, you are going to implement the word guessing game, Hangman 2.0. Your program is going to get a random word from an enumerated list (instructions below) and then let the user

### Chapter 4: Control Structures I

Chapter 4: Control Structures I Java Programming: From Problem Analysis to Program Design, Second Edition Chapter Objectives Learn about control structures. Examine relational and logical operators. Explore

### IT115: Introduction to Java Programming 1. IT115: Introduction to Java Programming. Tic Tac Toe Application. Trina VanderLouw

IT115: Introduction to Java Programming 1 IT115: Introduction to Java Programming Tic Tac Toe Application Trina VanderLouw Professor Derek Peterson Colorado Technical University Online October 28, 2011

### Chapter 4: Conditionals and Recursion

Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Agenda The modulus operator Random Number Generation Conditional Execution Alternative

### Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

### (A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Ch 5 Arrays Multiple Choice Test 01. An array is a ** (A) data structure with one, or more, elements of the same type. (B) data structure with LIFO access. (C) data structure, which allows transfer between

### Building Java Programs

Building Java Programs Chapter 5 Lecture 5-4: do/while loops, assertions reading: 5.1, 5.5 1 The do/while loop do/while loop: Performs its test at the end of each repetition. Guarantees that the loop's

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

CPS109 Course Notes 6 Alexander Ferworn Unrelated Facts Worth Remembering Use metaphors to understand issues and explain them to others. Look up what metaphor means. Table of Contents Contents 1 ITERATION...

### Loops. Repeat after me

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 repeat is determined by the value of a control variable,

### Building Java Programs

Building Java Programs Chapter 5 Lecture 5-2: Random Numbers reading: 5.1, 5.6 1 http://xkcd.com/221/ 2 Randomness Lack of predictability: don't know what's coming next Random process: outcomes do not

### Algorithms and Conditionals

Algorithms and Conditionals CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/