AP CS Unit 3: Control Structures Notes

Similar documents
Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Exercises

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

Practice Midterm 1 Answer Key

Important Java terminology

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

CS110: PROGRAMMING LANGUAGE I

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

M e t h o d s a n d P a r a m e t e r s

4. Java Project Design, Input Methods

AP Computer Science Unit 1. Programs

NATIONAL UNIVERSITY OF SINGAPORE

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

Lecture 5: Methods CS2301

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Practice Midterm 1. Problem Points Score TOTAL 50

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

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

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

Mr. Monroe s Guide to Mastering Java Syntax

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

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

( &% class MyClass { }

The Math Class. Using various math class methods. Formatting the values.

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

Java Coding 3. Over & over again!

AP Computer Science Java Mr. Clausen Program 6A, 6B

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

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

AP Computer Science A Unit 2. Exercises

Java Classes: Math, Integer A C S L E C T U R E 8

Midterm Examination (MTA)

Lecture 6: While Loops and the Math Class

Advanced Java Concept Unit 1. Mostly Review

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

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

Lesson 5: Introduction to the Java Basics: Java Arithmetic THEORY. Arithmetic Operators

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

CS111: PROGRAMMING LANGUAGE II

Programming with Java

Chapter 3. Selections

CS141 Programming Assignment #6

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Chapter 5 Methods / Functions

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.

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

CS 200 Using Objects. Jim Williams, PhD

CS111: PROGRAMMING LANGUAGE II

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

Topics. Chapter 5. Equality Operators

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CT 229 Java Syntax Continued

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

Chapter 6 Methods. Dr. Hikmat Jaber

AP Computer Science Unit 1. Writing Programs Using BlueJ

Conditionals, Loops, and Style

CONDITIONAL EXECUTION

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Java I/O and Control Structures

Supplementary Test 1

APCS Semester #1 Final Exam Practice Problems

AP Computer Science Unit 1. Writing Programs Using BlueJ

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Methods and Functions

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Building Java Programs

Java I/O and Control Structures Algorithms in everyday life

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Pace University. Fundamental Concepts of CS121 1

Computer Programming I - Unit 2 Lecture 1 of 13

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

AP COMPUTER SCIENCE A

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Advanced Object Concepts

Introduction to Software Development (ISD) Week 3

Assignment 2.4: Loops

More on variables, arrays, debugging

1.3 Conditionals and Loops

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

AP Computer Science A

Using Java Classes Fall 2018 Margaret Reid-Miller

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

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Variables and data types

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

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

CS115 Principles of Computer Science

DM503 Programming B. Peter Schneider-Kamp.

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

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Unit 4: Classes and Objects Notes

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Transcription:

AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts refer to them as conditionals because they represent a condition that may be or. x > 8 x = x + 2 n 5 n = n - 1 n = 3 * n Boolean Expressions A Boolean expression is an expression that is either or. For example: x >= 8 The above expression compares x to 8. If x is greater than or equal to 8, then the expression is. Otherwise the expression is. Java uses 6 relational operators in its Boolean expressions. _ Page 1

Logical Operators. More complicated Boolean expressions can be composed through the use of logical operators such as AND and OR. The following table shows how certain expressions can be written. English Mathematically Java A number is greater than 0 and less than or equal to 5. A number is less than 12 or greater than 65 Example. Complete the code to the right based on the flowchart below. k++ k = k + 2 3 < k < 7 k = k - 3 k 5 display k k-- k = 2 * k public class Example { public static void main(string[] args) { Scanner x = new Scanner( System.in ); System.out.print("Enter an integer "); int k = x.nextint(); Page 2

The Math Class. The Math Class contains a collection of standard math functions. Here are some examples on how to use them. To take the square root of a number: double a = Math.sqrt( 16 ); a = Math.sqrt( a ); To raise a number to nth power: double b = Math.pow( 2, 3 ); double c = Math.pow( b, 2.0 ); int d = (int) Math.pow( 3, 4 ); // a equals // a equals // equivalent to, b equals // c equals // d equals Math.pow always returns a double. To take the absolute value: int e = Math.abs( -17 ); double f = Math.abs( -45.8 ); To generate a random decimal between 0 (inclusive) and 1 (exclusive): double g = Math.random(); double h = 5 * Math.random(); // // To generate a random integer from min (inclusive) and max (inclusive), use the following formula: int num = (int) ( range * Math.random() ) + min; // where range = max min + 1 For example, to generate a random integer between -3 and 5: int num = (int) ( 9 * Math.random() ) - 3; // num will be -3 or -2 or 4 or 5 1. a is a random decimal within these limits a < double a = 10 * Math.random() - 3; 2. b is a random integer within these limits b int b = (int)( 5 * Math.random() ) + 3; 3. c is a random integer within these limits c int c = (int)( 12 * Math.random() ); 4. d is a random integer within these limits The abs method is overloaded. This means that are more than one method with the same name but different parameters and return types. d int d = (int)( 3 * Math.random() ) - 7; Page 3

if-else if Statements. The basic if - else structure can be expanded to handle multiple conditionals through the use of else-if statements. For example, if you want to determine if a grade is an A, B, C, D, or E, a simple if - else statement won't work. 0 age<13 age<20 age<120 print "???" print "child" print "teen" print "adult" done get cost get id cost > 100 id = 13 print cost reduce cost by 10% reduce cost by 5% public class Example { public static void main(string[] args) { Scanner sc = new Scanner( System.in ); System.out.print("Enter cost "); double cost = sc.nextdouble(); System.out.print("Enter id "); int id = sc.nextint(); IMPORTANT. Page 4

While Loops. A while loop is a control structure that allows you to write code that is executed repeatedly as long as some condition is. int n = 2; while( n <= 5 ) { System.out.println(n + "cats"); n++; Every pass through the body of a loop is called an. double money = 1000.0; int numyears = 0; Scanner get = new Scanner( System.in ); System.out.print( "Enter your goal: " ); double goal = get.nextdouble(); System.out.println( numyears + " years "); System.out.println( money + " dollars "); You have $1,000 and a 10% interest rate. Calculate how many years must pass until your money has reached (or surpassed) some goal money = 1,000; numyrs = 0; get $ goal from user money < goal calculate interest increase money numyrs++ display numyears and money Page 5

The Break Statement. The break statement causes a loop to end immediately. For example: int x = 0; while ( x >=0) { x = (int)( 100 * Math.random() ); if (x % 10 == 0 ) break; System.out.println( x ); // x // what may be displayed? Block Scope. In our earlier programs, a variable existed from the line where we declared it until the end of the program (remembering that all of our programs consist of just the main method). If a variable is declared within a pair of curly braces (for example, after an if or while statement), it only exists within those curly braces. This is called block scope. public class A{ public static void main( String[] args ){ Scanner in = new Scanner( System.in ); System.out.println( "How many waffles?"); int n = in.nextint(); if ( n > 3 ){ int extra = (int) (5*Math.random()+1 ); n = n + extra; System.out.println( "You get " + n + "!" ); Program A public class B{ public static void main( String[] args ){ Scanner in = new Scanner( System.in ); System.out.println( "How many waffles?"); int n = in.nextint(); if ( n > 3 ){ int extra = (int) (5*Math.random()+1 ); n = n + extra; System.out.println( "You get " + n + "!" ); Program B Which of the above programs compile? Which one does not compile? Would anything change if the curly brackets associated with the if statement in Program A were deleted? Page 6

For Loops. A for-loop is typically used when you need to repeat a process a specific number of times. The first statement in a for-loop contains three statements separated by semicolons: 1. 2. 3. for ( int n = 1; n < 4; n++) { // the body of the loop Example 1. What does this loop display? for ( int k = 5; k <= 8; k++ ){ System.out.print( k + " " ); Example 2. What does this loop display? for ( int n = 25; n >= 10; n = n - 7 ){ System.out.print( n + " " ); Example 3. What does this loop display? for ( int k = 1; k < 10; k++ ){ if ( k % 5 == 0 ) break; System.out.print( k + " " ); Page 7