# Chapter 4: Conditionals and Recursion

Size: px
Start display at page:

Transcription

1 Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist by Allen B. Downey

2 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals: the return statement Recursion 2

3 Calculate leftover inches In assignment 3 we wanted to convert: inches feet and leftover inches. For example, 40 inches = 3 feet, 4 inches We used these formulae: feet = inches/12 (using integer division) leftover_inches = inches feet*12 feet = *12 = 4 There's a better way to calculate leftover_inches: Modulus operator (%) leftover_inches = inches % 12 ;

4 Modulus Operator The modulus operator ONLY works on integers yields the remainder of first divided by second. In Java, the modulus operator is % int quotient = 7 / 3; // 2 int remainder = 7 % 3; // 1 Thus, 7 divided by 3 is 2 with 1 left over. Use to check if one number divisible by another if x % y is zero, then x is divisible by y. Solve these on your lab4 handout: 25 % 8 = 37 % 10 = 4 % 7 = 125 % 25 = 8 % 4 = 7 % 4 = 4

5 Modulus Operator The modulus operator ONLY works on integers yields the remainder of first divided by second. In Java, the modulus operator is % int quotient = 7 / 3; // 2 int remainder = 7 % 3; // 1 Thus, 7 divided by 3 is 2 with 1 left over. Use to check if one number divisible by another if x % y is zero, then x is divisible by y. For example: 25 % 8 = 1 37 % 10 = 7 4 % 7 = % 25 = 0 8 % 4 = 0 7 % 4 = 3

6 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 6

7 Random Number Generation Java's Math library has a method random generates a random number between 0 and 1 0 <= x < 1 Here's how to use it: double x = Math.random(); System.out.println( x ) Each time you run the program, different x: Useful for computer games, coin toss, etc.

8 Modeling a Coin Toss Pick a random number, mynumber If mynumber is less than 0.5, print "heads" If mynumber is larger than 0.5, print "tails" We need a new programming structure that lets us print a different message depending on the value of mynumber!

9 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 9

10 Which way to go? Conditional statements allow execution of certain statements only if a particular condition is satisfied Consider these statements as some kind of a gate keeper that allows entry only if a condition is satisfied 10

11 Conditional Execution The if statement decides whether a section of code executes or not. changes the behavior of the program accordingly. if (expression is true) execute statement block if the expression is false, nothing happens 11

12 Flowcharts If statements can be modeled as a flow chart. if (temp < 32){ wearcoat(); Is it cold outside? Yes Wear a coat. 12

13 Relational Operators In most cases, the condition of the if statement is written using relational operators. Relational Operator Meaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to!= is not equal to 13

14 Relational Operators A condition is a relational expression formed from one of the 6 relational operators. results in a true or false value. Expression Meaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y. x == y Is x equal to y? x!= y Is x not equal to y? 3-14

15 Conditional examples: This if statement assigns 0 to x when y is equal to 20 if (y == 20) { x = 0; If hours is larger than 40, then pay gets the value payrate times 1.5 times hours if (hours > 40) { pay = payrate*1.5*hours

16 Example: Modeling a Coin Toss, Version 1 double mynumber = Math.random(); //Decide the outcome of a coin flip if (mynumber <.5) { System.out.println("heads"); if (mynumber >=.5) { System.out.println("tails"); Every time we run the program, we get a different mynumber (between 0 and 1) The first if prints "heads" if mynumber < 0.5 The second if prints "tails" if mynumber >= 0.5

17 Caution with Conditionals Syntax differs from math symbols: =, and. common error: single = instead of a double == = is the assignment operator == is a comparison operator. no such thing as =< or =>. Two sides of a condition must be same type. Only compare ints to ints and doubles to doubles. == and!= don't work with Strings like you expect. Comparing strings is in chapter 8

18 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 18

19 Alternative Execution The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementblockiftrue; else statementblockiffalse; 3-19

20 if-else Statement Flowcharts No Is it cold outside? Yes Wear shorts. Wear a coat. if (temp < 32){ wearcoat(); else { wearshorts(); 3-20

21 Example: Modeling a Coin Toss, Version 2 double x = Math.random(); if (x < 0.5) { System.out.println("heads"); else { System.out.println("tails"); Every time we run the program, we get a different x (between 0 and 1) The if statement prints "heads" if x < 0.5 Note: else handles the case that x is NOT < 0.5 do not say else (x >= 0.5) { ERROR

22 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 22

23 Chained Conditionals if (expression_1) { statement; statement; etc. else if (expression_2) { statement; statement; etc. If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. Insert as many else if clauses as necessary else { statement; statement; etc. These statements are executed if none of the expressions above are true. 3-23

24 Chained Conditionals (if-else-if) Chained conditionals using the if-else-if statement makes it possible to handle more than two possible outcomes handle as many as you like Continue to add else-if blocks until you run out of possibilities Last else means "none of the above" were true Care must be used since else statements match up with the immediately preceding unmatched if statement. 3-24

25 Chained Conditional (if-else-if) Flowchart 3-25

26 Chained Conditional (if-else-if) Example if (x > 0) { System.out.println("x is positive"); else if (x < 0) { System.out.println("x is negative"); else { System.out.println("x is zero"); keep all the statements and squiggly-brackets lined up less likely to make syntax errors more likely to find them if you do 3-26

27 What if our Coin could fall off the table? double x = Math.random(); if (x < 0.45) { System.out.println("heads"); else if (x < 0.9) { System.out.println("tails"); else { System.out.println("fell off table!"); Prints "heads": 0.0 <= x < 0.45 Prints "tails": 0.45 <= x < 0.9 Prints "fell off table": 0.90 <= x < 1.0

28 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 28

29 Nested Conditonals If an if statement appears inside another if statement block it is called a nested conditional The nested if is executed only if the outer if statement results in a true condition. Nesting allows for unlimited variation of structure in selecting possible outcomes. Can also be harder to read 3-29

30 Nested if Statement Flowcharts No Is it cold outside? Yes Wear shorts. No Is it snowing? Yes Wear a jacket. Wear a parka. 3-30

31 Nested Conditional Example if (coldoutside){ if (snowing){ wearparka(); else{ wearjacket(); else{ wearshorts(); 3-31

32 Style helps clarify logic proper indentation makes it much easier to match up else statements with their corresponding if statement. Bad example: if (coldoutside){ if (snowing) { wearparka(); else { wearjacket(); else { wearshorts(); 3-32

33 Alignment and Nested if Statements This if and else go together. This if and else go together. if (coldoutside) { if (snowing) { wearparka(); else { wearjacket(); else { wearshorts(); 3-33

34 Do Lab 4 Part A finish PennyChanger debug AgeInsult we'll cover Scanner in next lecture used to input data from keyboard write CoinFlip program If you finish early, start doing drills in Assignment 4 Please do not do Part B until after next lecture

35 Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 35

36 The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.scanner; 2-36

37 The Scanner Class Scanner objects work with System.in To create a Scanner object: Scanner keyboard = new Scanner (System.in); The following Scanner class methods are useful next read the next word (til whitespace) as String nextline read to the end of line as a String nextint read the next number as an int nextdouble read the next number as a double See example on next slide 2-37

38 import java.util.scanner; // Needed for the Scanner class /** This program demonstrates the Scanner class. */ public class Payroll { public static void main(string[] args) { String name; // To hold a name int hours; // Hours worked double payrate; // Hourly pay rate double grosspay; // Gross pay // Create a Scanner object to read input. Scanner keyboard = new Scanner(System.in); // Get the user's name. System.out.print("What is your name? "); name = keyboard.nextline(); Read 1 line of text name = keyboard.next( ); // reads one word of text

39 // Get the number of hours worked this week. System.out.print("Number of hours worked this week? "); hours = keyboard.nextint(); // Get the user's hourly pay rate. System.out.print("What is your hourly pay rate? "); payrate = keyboard.nextdouble(); // Calculate the gross pay. grosspay = hours * payrate; Read 1 integer value Read 1 double // Display the resulting information. System.out.println("Hello " + name); System.out.println("Your gross pay is \$" + grosspay);

40 Adding Conditionals to other methods This code checks whether x is divisible by 2 if (x%2 == 0) { System.out.println("x is even"); else { System.out.println("x is odd");

41 If you want to use it a lot, write a method This method checks whether x is divisible by 2 public static void printparity(int x){ if (x%2 == 0) { System.out.println("x is even"); else { System.out.println("x is odd"); This code invokes (calls) the method above printparity(15); printparity(24);

42 Reminder: do not declare variables in method calls printparity(7); int number = 35; printparity(number); printparity(int number); // WRONG

43 Return Statement lets you terminate the execution of a method early such as if you detect an error condition: public static void printsquareroot(double x) { if (x < 0.0) { System.out.println("Positive numbers only, please."); return; double result = Math.sqrt(x); System.out.println("The square root of x is " + result); checks whether x is less than zero, if so it prints an error message and then exits method. flow of execution returns to the caller remaining lines are not executed. 3-43

44 Automatic Type Conversion How does this work? "The square root of x is " + result one of the operands is a String, the other is a double. Java automatically converts the double to a String then joins them using string concatenation. What do you think would happen when adding an integer and a floating-point value? =??? 3-44

45 Recursion it is legal for one method to invoke another it is also legal for a method to invoke itself one of the most magical and interesting things program can do. public static void countdown(int n) { if (n == 0) { System.out.println("Blastoff!"); else { System.out.println(n); countdown(n-1); countdown takes a single integer as a parameter. If the parameter is zero, prints Blastoff. Otherwise, prints the number, & invokes countdown again, passing n-1 as an argument 3-45

46 Running a recursive countdown if we invoke this method, in main: countdown(3); it prints 3, then invokes itself on 2... it prints 2, then invokes itself on 1... it prints 1, then invokes itself on 0... it prints Blastoff!, then returns The countdown that got n=1 returns. The countdown that got n=2 returns. The countdown that got n=3 returns. And then you re back in main. Displays: Blastoff! 3-46

47 Another Recursive example recall newline and threelines from chapter 3 not very helpful if we want to print 2 lines or 106 a better alternative would be public static void nlines(int n) { if (n > 0) { System.out.println(""); nlines(n-1); if n is greater than zero, prints 1 newline then invokes itself to print n-1 newlines. The total number of newlines that get printed is 1 +(n-1), which usually comes out to roughly n! Recursion: when a method invokes itself 3-47

48 Stack Diagram for Recursive Methods stack diagrams can help interpret a recursive method. every time a method is called, get a new frame frame contains new method parameters and vars stack diagram for countdown, called with n = 3 public static void countdown(int n) { if (n == 0) { System.out.println("Blastoff!"); else { System.out.println(n); countdown(n-1); base case

49 Do Lab 4 Part B

### Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Chapter 4 Conditionals and recursion 4.1 The modulus operator The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second.

### Chapter 3: Decision Structures

Chapter 3: Decision Structures Chapter Topics Chapter 3 discusses the following main topics: The if Statement The if-else Statement Nested if statements The if-else-if Statement Logical Operators Comparing

### Chapter 3: Decision Structures

Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 3 discusses the following main topics: The if Statement

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

### Basic Computation. Chapter 2

Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

### A+ Computer Science -

import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()

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

### Repetition, Looping. While Loop

Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

### CS 302: Introduction to Programming

CS 302: Introduction to Programming Lectures 2-3 CS302 Summer 2012 1 Review What is a computer? What is a computer program? Why do we have high-level programming languages? How does a high-level program

### Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,

### Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.

### Full file at

Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

### Evaluating the Style of your programs

Evaluating the Style of your programs Objectives At the end of this exercise, students will: Roles Be able to evaluate a program for conformance to style guide for the class. Be able to evaluate arithmetic

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

### Basic Computation. Chapter 2

Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

### Control Structures: if and while A C S L E C T U R E 4

Control Structures: if and while A C S - 1903 L E C T U R E 4 Control structures 3 constructs are essential building blocks for programs Sequences compound statement Decisions if, switch, conditional operator

### Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Current Options for Storing Data 1) You need to store the room temperature, such as 62.5, in a variable. What

### Section 2: Introduction to Java. Historical note

The only way to learn a new programming language is by writing programs in it. - B. Kernighan & D. Ritchie Section 2: Introduction to Java Objectives: Data Types Characters and Strings Operators and Precedence

### Lecture Set 2: Starting Java

Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

### Oct Decision Structures cont d

Oct. 29 - Decision Structures cont d Programming Style and the if Statement Even though an if statement usually spans more than one line, it is really one statement. For instance, the following if statements

### CMSC131. Introduction to your Introduction to Java. Why Java?

CMSC131 Introduction to your Introduction to Java Why Java? It s a popular language in both industry and introductory programming courses. It makes use of programming structures and techniques that can

### Lecture Set 2: Starting Java

Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

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

Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in

### BASIC INPUT/OUTPUT. Fundamentals of Computer Science

BASIC INPUT/OUTPUT Fundamentals of Computer Science Outline: Basic Input/Output Screen Output Keyboard Input Simple Screen Output System.out.println("The count is " + count); Outputs the sting literal

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

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

### A+ Computer Science -

Visit us at www.apluscompsci.com Full Curriculum Solutions M/C Review Question Banks Live Programming Problems Tons of great content! www.facebook.com/apluscomputerscience import java.util.scanner; Try

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

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

Lab1 Solution MathTrick.java /** * MathTrick Lab 1 * * @version 8/25/11 * Completion time: 10-15 minutes public class MathTrick public static void main(string [] args) int num = 34; //Get a positive integer

### What did we talk about last time? Examples switch statements

Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

### More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

More Things We Can Do With It! More operators and expression types More s 11 October 2007 Ariel Shamir 1 Overview Variables and declaration More operators and expressions String type and getting input

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

### Chapter 7. Iteration. 7.1 Multiple assignment

Chapter 7 Iteration 7.1 Multiple assignment You can make more than one assignment to the same variable; effect is to replace the old value with the new. int bob = 5; System.out.print(bob); bob = 7; System.out.println(bob);

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

### AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

AP Computer Science Return values, Math, and double Distance between points Write a method that given x and y coordinates for two points prints the distance between them If you can t do all of it, pseudocode?

### CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I 06 / 02 / 2015 Instructor: Michael Eckmann Today s Topics Operators continue if/else statements User input Operators + when used with numeric types (e.g. int,

### Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

### Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #2

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

### Data Conversion & Scanner Class

Data Conversion & Scanner Class Quick review of last lecture August 29, 2007 ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev Numeric Primitive Data Storing

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

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

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

### Example Program. public class ComputeArea {

COMMENTS While most people think of computer programs as a tool for telling computers what to do, programs are actually much more than that. Computer programs are written in human readable language for

### CS 112 Introduction to Programming

CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

### CS 112 Introduction to Programming

CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

### COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

### Data Structure and Programming Languages

204700 Data Structure and Programming Languages Jakarin Chawachat From: http://ocw.mit.edu/courses/electrical-engineering-and-computerscience/6-092-introduction-to-programming-in-java-january-iap-2010/index.htm

### CONDITIONAL EXECUTION

CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I Outline Conditional Execution if then if then Nested if then statements Comparisons

### Chapter 3 Selections. 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. 0132130807 1 Motivations If you assigned a negative value for radius

### Input. Scanner keyboard = new Scanner(System.in); String name;

Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.

### Chapter 2. Elementary Programming

Chapter 2 Elementary Programming 1 Objectives To write Java programs to perform simple calculations To obtain input from the console using the Scanner class To use identifiers to name variables, constants,

### Chapter 1 Lab Algorithms, Errors, and Testing

Chapter 1 Lab Algorithms, Errors, and Testing Lab Objectives Be able to write an algorithm Be able to compile a Java program Be able to execute a Java program using the Sun JDK or a Java IDE Be able to

### Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CS256 Computer Science I Kevin Sahr, PhD Lecture 25: Miscellaneous 1 main Method Arguments recall the method header of the main method note the argument list public static void main (String [] args) we

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

### Building Java Programs

Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 1 Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 2 Data types type: A category or set of data

### Basic Operations jgrasp debugger Writing Programs & Checkstyle

Basic Operations jgrasp debugger Writing Programs & Checkstyle Suppose you wanted to write a computer game to play "Rock, Paper, Scissors". How many combinations are there? Is there a tricky way to represent

### CS 112 Introduction to Programming

CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin

### Condi(onals and Loops

Condi(onals and Loops 1 Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > = == 2 A Founda(on for Programming any program

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

### Building Java Programs

Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading: 2.1-2.2 Copyright 2009 by Pearson Education Data and expressions reading: 2.1 self-check: 1-4 videos: Ch. 2 #1 Copyright

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

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

COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

### Anatomy of a Java Program: Comments

CS149 Anatomy of a Java Program: Comments Javadoc comments: /** * Application that converts inches to centimeters. * * @author Alvin Chao * @version 01/21/2014 */ Everything between /** and */ ignored

### CEN 414 Java Programming

CEN 414 Java Programming Instructor: H. Esin ÜNAL SPRING 2017 Slides are modified from original slides of Y. Daniel Liang WEEK 2 ELEMENTARY PROGRAMMING 2 Computing the Area of a Circle public class ComputeArea

### Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

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

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

### Task #1 The if Statement, Comparing Strings, and Flags

Chapter 3 Lab Selection Control Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare Strings Be able to use a flag Be able to construct if

### Introduction to Java Applications

2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

### Lecture 2: Operations and Data Types

Lecture 2: Operations and Data Types Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. Data types type: A category or set

### BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development

### 1 Short Answer (10 Points Each)

1 Short Answer (10 Points Each) 1. Write a for loop that will calculate a factorial. Assume that the value n has been input by the user and have the loop create n! and store it in the variable fact. Recall

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

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

### PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

PRG PROGRAMMING ESSENTIALS 1 Lecture 2 Program flow, Conditionals, Loops https://cw.fel.cvut.cz/wiki/courses/be5b33prg/start Michal Reinštein Czech Technical University in Prague, Faculty of Electrical

### Over and Over Again GEEN163

Over and Over Again GEEN163 There is no harm in repeating a good thing. Plato Homework A programming assignment has been posted on Blackboard You have to convert three flowcharts into programs Upload the

### AP Computer Science A

AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

### Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Decision Structures Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o Relational Operators o The if Statement o The if-else Statement o Nested if statements o The if-else-if

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

### Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Chapter 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

### 4. Java language basics: Function. Minhaeng Lee

4. Java language basics: Function Minhaeng Lee Review : loop Program print from 20 to 10 (reverse order) While/for Program print from 1, 3, 5, 7.. 21 (two interval) Make a condition that make true only

Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

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

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

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

### COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.

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

### Assignment 2.4: Loops

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

### Reading Input from Text File

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014 The simplest

### Topic 12 more if/else, cumulative algorithms, printf

Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software,

### Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

### Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

### 1 Short Answer (5 Points Each)

1 Short Answer (5 Points Each) 1. What are the three types of programming errors? Briefly describe each of them. Syntax Error: An error in the program code due to misuse of the programming language. Run-time

### Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

### Building Java Programs

Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1, 4.5 2 Interactive Programs with Scanner reading: 3.3-3.4 Interactive programs We have written programs that print console

### First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1 Output System.out.println( ) prints out something. System.out.println is the first