Assignment 2.4: Loops

Similar documents
Chapter Goals. Contents LOOPS

Java Coding 3. Over & over again!

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

1 Short Answer (10 Points Each)

AP Programming - Chapter 6 Lecture

Chapter 4 Lab. Loops and Files. Objectives. Introduction

! 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

APCS Semester #1 Final Exam Practice Problems

Building Java Programs

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

AP CS Unit 3: Control Structures Notes

Introduction to Software Development (ISD) Week 3

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

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

Midterm Examination (MTA)

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

Introduction to the Java Basics: Control Flow Statements

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

Last Class. While loops Infinite loops Loop counters Iterations

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:

CS1150 Principles of Computer Science Loops (Part II)

Question: Total Points: Score:

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Chapter 4 Introduction to Control Statements

Nested Loops ***** ***** ***** ***** ***** We know we can print out one line of this square as follows: System.out.

Object-Oriented Programming

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.

Introduction to Computer Science Unit 3. Programs

Iteration statements - Loops

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

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Lecture 14. 'for' loops and Arrays

Problem Solving With Loops

STUDENT LESSON A12 Iterations

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Control Flow: Loop Statements

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

Welcome to the Using Objects lab!

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

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

CS Week 5. Jim Williams, PhD

Repetition, Looping. While Loop

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

Top-Down Program Development

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Building Java Programs

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

CSE143 Notes for Monday, 4/25/11

Arrays OBJECTIVES. In this chapter you will learn:

Java I/O and Control Structures

Repetition Structures

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

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

Module 2: Choice and Iteration

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Controls Structure for Repetition

Introduction to Java & Fundamental Data Types

CompSci 125 Lecture 11

What did we talk about last time? Examples switch statements

switch-case Statements

COMP 202 Java in one week

RANDOM NUMBER GAME PROJECT

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Chapter 3. Selections

AP Computer Science A

CS 302: Introduction to Programming

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

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

CSE 1223: Exam II Autumn 2016

Welcome to the Using Objects lab!

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

5) (4 points) What is the value of the boolean variable equals after the following statement?

int x = 42, y = 33; //1 int z = x + y; //2 System.out.println(x + "+" + y + "=" + z); //3

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Repetition. Chapter 6

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Repetition. Chapter 6

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Chapter 3: Operators, Expressions and Type Conversion

Example: Monte Carlo Simulation 1

CSCI 355 Lab #2 Spring 2007

Values in 2 s Complement

Chapter 4: Conditionals and Recursion

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Transcription:

Writing Programs that Use the Terminal 0. Writing to the Terminal Assignment 2.4: Loops In this project, we will be sending our answers to the terminal for the user to see. To write numbers and text to the Terminal, use System.out.print() and System.out.println(). Println writes the code to the terminal and adds a line break at the end, where as print does not add the line break. Here are some examples: //Print text //System.out.println( What is the meaning of life? ); //Print the value of a variable: System.out.println(count); //Print the value of a variable and text: System.out.println( You have played this game + count + times! ); Make sure you find out the difference between these two sets of statements: System.out.print( Hello ); System.out.print( Hello ); System.out.println( Hello ); System.out.println( Hello ); 1. Reading User Input from the Terminal In this project, the user will be able to interact with your program by typing in responses in the Terminal. We will use the Scanner class to accomplish this. Note that reading user input is not part of the AP Exam and will never be tested, but it will be important to understand to make many projects work during the course. In the assignment, a Scanner object called input has been declared and initialized already for you. Here are some examples of how to use it: int n = input.nextint(); //reads an int from terminal and stores it double val = input.nextdouble(); //same, but for decimal values String ans = input.next(); //stores text It is often important to include a prompt to tell the user what information you expect. Using print instead of println means the question can be answered on the same line as the question. For example: System.out.print( What is your name? );

String name = input.next(); System.out.println( Hello + name); 2. Checking if the Value of Strings If you want to see if a String variable has a certain value, you cannot use the == operator. We will discuss this more in the future Strings unit. For now, you need to use the following technique: RIGHT String ans = input.nextline(); if (ans.equals( yes )) System.out.println( YESSS! ); else if (ans.equals( no )) System.out.println( NOOOO! ); WRONG String ans = input.nextline(); if (ans == yes ) System.out.println( YESSS! ); else if (ans == no ) System.out.println( NOOOO! ); 3. Generating Random Numbers The Math class includes the method Math.random() which returns a number between 0 (inclusive) and 1 (exclusive). To generate a number in a different range, you need to use multiplication and addition to shift this range. If you want to create random integers, you will need to use casting operators to remove the decimal components. An Example Program That Uses the Terminal Here is an example method that interacts with the user in the terminal to convert between centimeters and inches: public void inchestocm() double cm; int feet, inches, remainder; double CM_PER_INCH = 2.54; int IN_PER_FOOT = 12; // prompt the user and get the value System.out.print("Exactly how many cm? "); cm = in.nextdouble(); // convert and output the result inches = (int) (cm / CM_PER_INCH); feet = inches / IN_PER_FOOT; remainder = inches % IN_PER_FOOT; System.out.print(cm + cm = + feet + ft, + inches + in );

For Loops A for loop is used to repeat a set of instructions. Here is an example. Please read it carefully and try to figure out what it does before reading on. Example 1: for (int i = 1; i<=10; i++) System.out.println(i); Check your answer at the end Parts of a For Loop Intialization Statement Conditional Statement Iterator Initialization Statement for (int i = 1; i<=10; i++) System.out.println(i); Body contains task to be repeated The Initialization Statement creates a variable to keep track of how many times we have repeated the loop, and what value we will start counting from. In this case, we call this variable i and we start counting from 1. The initialization statement only happens the first time we start the loop, not every time we go through the loop. Conditional Statement The Conditional Statement is a boolean (true or false) expression that determines if we repeat the loop or not. The statement evaluates to true, the task will be repeated another time. If it is false, the loop will stop. The Conditional Statement is checked every time it repeats the loop, including the FIRST time through the loop. So, it is possible that the body of the loop doesn't even get to run once. Iterator The Iterator is how we are counting as we go through the loop. The code i++ is short for add 1 to i, which means we are counting by ones. You could replace this with other statements, such as i-- to count down by 1 or i = i * 2 to double i every time.

How A Loop Works in Detail Initialization Statement (only happens once) Check conditional Statement True False Do the statements in the Body of the Loop Iterator Exit Loop Using this flowchart, we can see that the output from our example loop will be: 12345678910 While Loops While loops are the most used loop in Java. It is the simplest and most versatile loop. while (true) Conditional Statement System.out.print("!"); Body contains task to be repeated As long as the conditional statement is true, the loop will repeat the statements in the body of the loop. The flow chart for this kind of loop looks like this:

Check conditional Statement True False Do the statements in the Body of the Loop Exit Loop If the conditional statement is false at the beginning of the loop, then the loop will not execute the statements in the body of the loop even once. All for loops can also be written as while loops. For example, this for loop: for (int count = 0; count < 11; count++) System.out.println("Count is: " + count); Can be written as the following while loop: int count = 0; while (count < 11) System.out.println("Count is: " + count); count++; Take some time to trace through this loop and understand how the two loops work the same. As you can see, for loops are simpler for repeating a task a set number of times. However, while loops can be like "forever if" loops in scratch. They will continue to repeat something until the condition is false.

Here is an example of a while loop that does not repeat a task a set number of times, but keeps doing the task until some condition becomes false. 1 public void whiletest() 2 3 Scanner input = new Scanner(System.in); 4 5 String answer = "Mike"; 6 7 while (answer.equals("mike")) 8 9 System.out.print("What's your name, Mike? "); 10 answer = input.next(); 11 12 System.out.print("Hello, " + answer); 13 A sample of the output of the program is as follows: What's your name, Mike? Mike What's your name, Mike? Mike What's your name, Mike? Mike What's your name, Mike? Bob Hello, Bob Think about the answer to these question about the above loop. If you don't know the answers, ask for help! On line 5, we initialize the variable answer to "Mike". What would have happened if we set it to "Bob"? How does Java know when to stop the loop and move on to the next statements?

Nested Loops A nested loop is where you have a loop as a statement in the body of another loop. For example: for (int k = 0; k <= 3; k++) for (int i = 0; i < 4; i++) System.out.print( > ); System.out.println( ); In this case, the inside loop, which produces a row of four greater-than signs like this: >>>> is repeated 3 times, each time, adding a line break at the end. The result will be: >>>> >>>> >>>> Consider this for loop: EXERCISE 1: for (i = 100; i >= 10; i--) System.out.println("i is: " + i); Rewrite this as a while loop. What is the output of this loop? EXERCISE 2: for (i = 1; i <= 10; i++) for (j = 1 ; j <= i; j++) System.out.print(j + " "); System.out.println("");

EXERCISE 3: Write class RunningTally that repeatedly asks the user to enter an integer until the users gives a negative integer. At that point, the program prints out the total of all the numbers that the user entered (not including the negative). For example: Let's add some numbers! [Type a negative number to quit] Add: 4 Add: 6 Add: 2 Add: -1 Your total is 12. Note: Although the total is displayed at the end, it is important to update the total every time the user enters a new number. EXERCISE 4: Write class Bar that asks a user for a String char and an int x. The program then prints out a row of chars that is as long as x. For example, your program would look like this: What character do you want your bar made of? * How long do you want your bar? 7 Here's your bar! *******

EXERCISE 5: Write class Triangle that asks a user for a String char and an int x. Then the program prints out a right triangle of chars that is as tall as x. For example: What character do you want your triangle made of? * How tall do you want your triangle? 5 Here's your triangle! * ** *** **** ***** ****** This will require a nested for loop (a for loop inside a for loop). EXERCISE 6: Cut and paste your old D6 program into this project. Change your code so that it is contained within a loop. Change it so it runs like the following output: How many D6's do you want to roll? 3 You rolled: 2 5 4 Total: 11 Again? [y,n] y How many D6's do you want to roll? 5 You rolled: 1 2 1 3 4 Total: 11 Again? [y,n] n Good-bye!

EXERCISE 7: Write class GuessingGame that simulates a the "Guess What Number I'm Thinking Of" game. In this game, the computer picks a random number between 1 and 100. Then, the method will begin a loop, asking the user to guess the number. After each guess, the method will tell the user whether the guess was too high or too low, and then repeat the process. If the user guesses correctly, the loop will stop and the method will then display a congratulatory message and tell you how many tries it took you to guess the correct answer. Sample output is as follows: I've picked a random number between 1 and 100. Try to guess it! What is your guess? 50 Too high... What is your guess? 25 Too high... What is your guesss? 12 Too low... What is your guess? 16 You've guessed my number! Good job! It only took you 4 tries.