Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Size: px
Start display at page:

Download "Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring"

Transcription

1 Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

2 Review of Java Basics Data Types Arrays NEW: multidimensional arrays Boolean Expressions Conditionals: if-else NEW: switch Iteration: while and for loops NEW: alternate for loop syntax NEW: break and continue Recursion CSCI 136: Fundamentals of Computer Science II, Spring

3 Variables Primitive (and Basic) Data Types and Operations Type Conversion CSCI 136: Fundamentals of Computer Science II, Spring

4 int a; a = 10; int b; b = 7; int c = a + b; Declaration statement I'm going to need an integer and let's call it a NOTE: in Java you are required to declare a variable before using it! Variable name Whenever I say a, I mean the value stored in a Literal I want the value 10 Assignment statement Variable b gets the literal value 7 = in CS is not the same as = in math! Combined declaration and assignment Make me an integer variable called c and assign it the value obtained by adding together a and b CSCI 136: Fundamentals of Computer Science II, Spring

5 Java built-in type String what it stores example values sequence of characters "Hello world!" "I love this!" operations concatenate char characters 'a', 'b', '!' compare int integer values double floatingpoint values e8 boolean truth values true false add, subtract, multiply, divide, remainder add, subtract, multiply, divide and, or, not Remember a data type is a set of legal values and the operations defined on those values 5

6 Automatic conversion Numeric types: If no loss of precision automatic promotion String concatenation using the + operator converts numeric types to also be a String Converting from one type to another: Manually using a cast A cast is accomplished by putting a type inside ()'s ordertotal = (int) (costitem * 1.06); Casting to int drops fractional part Does not round! Using Static Methods int qty = Integer.parseInt(args[1]); double cst = Double.parseDouble(args[2]); 6

7 Single Dimensional (1D) Arrays Two Dimensional (2D) Arrays Multi-Dimensional (3+D)Arrays CSCI 136: Fundamentals of Computer Science II, Spring

8 x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[i] Declare and create: Check length: x int [] x = new int[7]; x.length Set a value: x[0] = 0; Obtain a value: x[0], x[1],..., x[6] 8

9 Declaring and creating Like 1D, but another pair of brackets: final int DAYS = 7; final int HOURS = 24; double [][] a = new double[days][hours]; Accessing elements To specify element at the i th row and j th column: a[i][j] How many rows? How many columns in a row? a.length a[row].length a[0][0] a[0][1] a[0][2]... a[0][22] a[0][23] a[1][0] a[1][1] a[1][2] a[1][22] a[1][23] 9

10 An array element can be an array 2D array is really an array of arrays a[0][0] a[0][1] a[0][2] a[0][3]... a[0][22] a[0][23] a[1][0] a[1][1] a[1][2] a[1][3]... a[1][22] a[1][23] a[0] a[1] a[2] a[3] a[4] a[5] a[6] 10

11 Arrays can have > 2 dimensions Use as many []'s as dimensions e.g. Game with a building consisting of 10 floors, each floor being a grid of 100 x 100 positions final int X_MAX = 100; final int Y_MAX = 100; final int FLOORS = 10; Avatar [][][] avatars = new Avatar[X_MAX][Y_MAX][FLOORS]; // Create the first player in the middle of the first floor avatars[49][49][0] = new Avatar(); 11

12 Results of Comparisons Logical Operators Combining Operations CSCI 136: Fundamentals of Computer Science II, Spring

13 Given two numbers return a boolean operator meaning true example false example == equal 7 == 7 7 == 8!= not equal 7!= 8 7!= 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 13

14 logical AND logical OR logical NOT &&! Note: two symbols for logical AND and OR uses lazy evaluation One symbol (&, ) forces full evaluation a b a && b a b false false false false a!a true false false true false true false true true false false true true true true true 14

15 if-else Nested if switch CSCI 136: Fundamentals of Computer Science II, Spring

16 Evaluate a boolean expression, inside the ()'s If true, do some stuff [optional] If false, do some other stuff if (expression) statement1; statement2; if (expression) statement1; statement2; else statement3; statement4; 16

17 Execute one of three options: if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; == if (category == 0) title = "Books"; else if (category == 1) title = "CDs"; else title = "Misc"; 17

18 Do something depending on a value value if-else if-else if... statements can get tedious Set a String variable monthstr to a string according to the integer value in the day variable. if (day == 1) monthstr = "Monday"; else if (day == 2) monthstr = "Tuesday"; else if (day == 3) monthstr = "Wednesday"; else if (day == 4) monthstr = "Thursday"; else if (day == 5) monthstr = "Friday"; else if (day == 6) monthstr = "Saturday"; else if (day == 7) monthstr = "Sunday"; else monthstr = "Invalid day!"; 18

19 switch statement Works with: byte, short, char, int, enumerations, String switch (day) case 1: monthstr = "Monday"; break; case 2: monthstr = "Tuesday"; break; case 3: monthstr = "Wednesday"; break; case 4: monthstr = "Thursday"; break; case 5: monthstr = "Friday"; break; case 6: monthstr = "Saturday"; break; case 7: monthstr = "Sunday"; break; default: monthstr = "Invalid day!"; break; case block normally ends with a break default block is optional, but if present executes if no other case matched. Like the else in an if-else if-else statement. 19

20 final int NORTH = 0; final int SOUTH = 1; final int EAST = 2; final int WEST = 3; int direction = 0; switch (direction) case NORTH: y--; System.out.println("Walking north"); break; case SOUTH: y++; System.out.println("Walking south"); break; case EAST: x++; System.out.println("Walking east"); break; case WEST: x--; System.out.println("Walking west"); break; You can have as many statements as you want between case and break. 20

21 final int NORTH = 0; final int SOUTH = 1; final int EAST = 2; final int WEST = 3; int direction = 0; switch (direction) case NORTH: y--; System.out.println("Walking north"); case SOUTH: y++; System.out.println("Walking south"); case EAST: x++; System.out.println("Walking east"); case WEST: x--; System.out.println("Walking west"); case block will fall through to next block if no break! Output: Walking north Walking south Walking east Walking west 21

22 int direction = 0; switch (direction) case NORTHWEST: case NORTHEAST: case NORTH: System.out.println("Heading northbound!"); break; case SOUTHWEST: case SOUTHEAST: case SOUTH: System.out.println("Walking southbound!"); break; Sometimes falling through to next case block is what you want. Easy way to do same thing for a set of discrete values. Output: Heading southbound 22

23 while loops while do while for loops non-enhanced enhanced break and continue CSCI 136: Fundamentals of Computer Science II, Spring

24 while loop: common way to repeat code Evaluate a boolean expression If true, do a block a code Go back to start of while loop If false, skip over block while (expression) statement1; statement2; while loop with multiple statements in a block while (expression) statement1; while loop with a single statement 24

25 do while loop Always executes loop body at least once Do a block a code Evaluate a boolean expression If expression true, do block again do statement1; statement2; while (condition); do while needs this semicolon! 25

26 for loop: another common type of loop Execute an initialization statement Evaluate a boolean expression If true, do code block then increment If false, done with loop for (init; expression; increment) statement1; statement2; 26

27 Declare and initialize a variable for use inside and outside the loop body long sum = 0; Condition which must be true to execute loop body Changes the loop counter variable Declare and initialize a loop control variable for (int i = 1; i <= limit; i++) sum += i; System.out.println("sum 0..." + i + " = " + sum); Loop body, executes 0 or more times 27

28 Enhanced for loop: another type of for loop for arrays Declare an iteration variable(var below) of the same type as the array Specify the array to step through (vararray below) The loop will perform the block of statements for each element of the array, with var taking on the value of the array element for (type var:vararray) statement1; statement2; 28

29 Example int [ ] arr = 0, 1, 2, 3, 4, 5; for (int x:arr) System.out.println(x+7); Output 29

30 Loops normally go until loop condition false break statement int i = 0 while (i < 100) // Do some stuff i++; for (int i = 0; i < 100; i++) // Do some stuff Exit a loop immediately No iteration, no increment No condition check Straight to the code after loop 30

31 break statement Terminates enclosing loop: for, while, or do-while Goal: sum data array, check for invalid negative values int [] data = 1, 2, 10, 5, -1, 5, 0; int i = 0; int sum = 0; while (i < data.length) if (data[i] < 0) break; sum += data[i]; i++; if (i < data.length) System.out.println("Invalid data!"); else System.out.println("Sum: " + sum); 31

32 Skip rest of for-loop, while-loop, do-while body Goal: sum data array, skipping invalid negative values int [] data = 1, 2, 10, 5, -1, 5, 0; int i = 0; int sum = 0; for (i = 0; i < data.length; i++) if (data[i] < 0) continue; sum += data[i]; System.out.println("Sum: " + sum); % java SumNumsSkip sum = 23 32

33 Mathematical Induction Base Case Inductive Step Recursion vs. Repetition CSCI 136: Fundamentals of Computer Science II, Spring

34 Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N 34

35 Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N Example: Prove T(N) = N = N(N + 1) / 2 for all N 35

36 Prove a statement involving an integer N Base case: Prove it for small N (usually 0 or 1) Induction step: Assume true for size N-1 Prove it is true for size N Example: Prove T(N) = N = N(N + 1) / 2 for all N Base case: T(1) = 1 = 1(1 + 1) / 2 36

37 Example: Prove T(N) = N = N(N + 1) / 2 for all N Base case: T(1) = 1 = 1(1 + 1) / 2 Induction step: Assume true for size N 1: N-1 = T(N - 1) = (N - 1)(N) / 2 T(N) = N-1 + N = (N 1)(N) / 2 + N = (N 1)(N) / 2 + 2N / 2 = (N 1 + 2)(N) / 2 = (N + 1)(N) / 2 37

38 Goal: Compute factorial N! = 1 * 2 * 3... * N N! = 1 for N=0 = (N-1)!*N otherwise Base case: 0! = 1 Induction step: Use (N 1)! to find N! public static long fact(long N) if (N == 0) return 1; return fact(n - 1) * N; 4! = 4 * 3 * 2 * 1 = 24 4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1 * 0! 0! = 1 base case induction step public static void main(string [] args) int N = Integer.parseInt(args[0]); System.out.println(N + "! = " + fact(n)); 38

39 public static long fact(long N) System.out.println("start, fact " + N); if (N == 0) System.out.println("end base, fact " + N); return 1; long step = fact(n - 1); System.out.println("end, fact " + N ); return step * N; start, fact 4 start, fact 3 start, fact 2 start, fact 1 start, fact 0 end base, fact 0 end, fact 1 end, fact 2 end, fact 3 end, fact 4 4! = 24 5 levels of fact() 39

40 Recursive algorithms also have an iterative version public static long fact(long N) if (N == 0) return 1; return fact(n - 1) * N; Recursive algorithm public static long fact(long N) long result = 1; for (int i = 1; i <= N; i++) result *= i; return result; Iterative algorithm Reasons to use recursion: Code is more compact and easier to understand Easer to reason about correctness Reasons not to use recursion: If you end up recalculating things repeatedly Processor with very little memory (e.g = 128 bytes) 40

41 Missing base case public static long fact(long N) return fact(n - 1) * N; No convergence guarantee public static double badidea(int N) if (N == 1) return 1.0; return badidea(1 + N/2) + 1.0/N; % java Factorial 5 Exception in thread "main" java.lang.stackoverflowerror at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8) at Factorial.fact(Factorial.java:8)... Both result in infinite recursion = stack overflow 41

42 Recursion: Brownian Landscape 42

43 Review of Java Basics Data Types Arrays NEW: multidimensional arrays Boolean Expressions Conditionals: if-else NEW: switch Iteration: while and for loops NEW: alternate for loop syntax NEW: break and continue Recursion CSCI 136: Fundamentals of Computer Science II, Spring

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen Other conditional and loop constructs Fundamentals of Computer Science Keith Vertanen Overview Current loop constructs: for, while, do-while New loop constructs Get out of loop early: break Skip rest of

More information

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming

More information

Recursion. Fundamentals of Computer Science

Recursion. Fundamentals of Computer Science Recursion Fundamentals of Computer Science Outline Recursion A method calling itself All good recursion must come to an end A powerful tool in computer science Allows writing elegant and easy to understand

More information

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3... Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial

More information

Variables and data types

Variables and data types Survivor: CSCI 135 Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

MODULE 02: BASIC COMPUTATION IN JAVA

MODULE 02: BASIC COMPUTATION IN JAVA MODULE 02: BASIC COMPUTATION IN JAVA Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment

More information

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args) Built-in data types logical AND logical OR logical NOT &&! public static void main(string [] args) Fundamentals of Computer Science Keith Vertanen Copyright 2013 Variables Variables and data types Stores

More information

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science Built-in data types logical AND logical OR logical NOT &&! public static void main(string [] args) Fundamentals of Computer Science Variables Overview Allows us to store and compute on data For now we'll

More information

Enumerations. Fundamentals of Computer Science

Enumerations. Fundamentals of Computer Science Enumerations Fundamentals of Computer Science Outline Avoiding magic numbers Variables takes on a small set of values Use descriptive names instead of literal values Java enumerations Using in a switch

More information

Java Review. Fundamentals of Computer Science

Java Review. Fundamentals of Computer Science Java Review Fundamentals of Computer Science Link to Head First pdf File https://zimslifeintcs.files.wordpress.com/2011/12/h ead-first-java-2nd-edition.pdf Outline Data Types Arrays Boolean Expressions

More information

Conditionals, Loops, and Style

Conditionals, Loops, and Style Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013 Control flow thus far public class ArgsExample public

More information

DATA TYPES AND EXPRESSIONS

DATA TYPES AND EXPRESSIONS DATA TYPES AND EXPRESSIONS Outline Variables Naming Conventions Data Types Primitive Data Types Review: int, double New: boolean, char The String Class Type Conversion Expressions Assignment Mathematical

More information

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression Conditionals, Loops, and Style Control flow thus far yes no x > y? max = x; max = y; public class ArgsExample time 0 String product = args[0]; time 1 int qty = Integer.parseInt(args[1]); time 2 double

More information

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Cellular Automata Language (CAL) Language Reference Manual

Cellular Automata Language (CAL) Language Reference Manual Cellular Automata Language (CAL) Language Reference Manual Calvin Hu, Nathan Keane, Eugene Kim {ch2880, nak2126, esk2152@columbia.edu Columbia University COMS 4115: Programming Languages and Translators

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Condi(onals and Loops

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

More information

Topic 5: Enumerated Types and Switch Statements

Topic 5: Enumerated Types and Switch Statements Topic 5: Enumerated Types and Switch Statements Reading: JBD Sections 6.1, 6.2, 3.9 1 What's wrong with this code? if (pressure > 85.0) excesspressure = pressure - 85.0; else safetymargin = 85.0 - pressure;!

More information

Computer Programming I - Unit 5 Lecture page 1 of 14

Computer Programming I - Unit 5 Lecture page 1 of 14 page 1 of 14 I. The while Statement while, for, do Loops Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly. The while statement is one of three looping statements

More information

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word Chapter 1 Introduction to Computers, Programs, and Java Chapter 2 Primitive Data Types and Operations Chapter 3 Selection

More information

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

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

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CS 61B Data Structures and Programming Methodology. June David Sun

CS 61B Data Structures and Programming Methodology. June David Sun CS 61B Data Structures and Programming Methodology June 25 2008 David Sun Announcements Visit 387 Soda to arrange for after hours access to Soda Hall. Computer Science Undergraduate Association event:

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015 Announcements Check the calendar on the course webpage regularly for updates on tutorials and office hours.

More information

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

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

More information

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Full file at

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

More information

Avoiding magic numbers

Avoiding magic numbers Avoiding magic numbers Variables takes on a small set of values Use descriptive names instead of literal values Java enumerations Using in a switch statement 2 Magic numbers Where did the value come from?

More information

CONDITIONAL EXECUTION

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

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit 2: Java in the small Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 Unit 2: Java in the small Introduction The previous unit introduced the idea of objects communicating through the invocation of methods

More information

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

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

More information

1.3 Conditionals and Loops

1.3 Conditionals and Loops 1 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond Math primitive data types

More information

Introduction to the Java Basics: Control Flow Statements

Introduction to the Java Basics: Control Flow Statements Lesson 3: Introduction to the Java Basics: Control Flow Statements Repetition Structures THEORY Variable Assignment You can only assign a value to a variable that is consistent with the variable s declared

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016 Review What is the difference between a while loop and an if statement? What is an off-by-one

More information

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

More information

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT:

Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( ) MUHAMMAD BILAL ( ) ISIT: Instructor: SIR MUHAMMAD NAVEED Created by: ARSLAN AHMED SHAAD ( 1163135 ) MUHAMMAD BILAL (1163122 ) ISIT:www.techo786.wordpress.com CHAPTER: 3 NOTE: CONTROL STATEMENTS Question s Given below are Long

More information

Unit 2: Java in the small

Unit 2: Java in the small Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 Introduction The previous unit introduced the idea of objects communicating through the invocation of methods on objects. In this unit you will learn: how to

More information

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2. Class #10: Understanding Primitives and Assignments Software Design I (CS 120): M. Allen, 19 Sep. 18 Java Arithmetic } Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = 2 + 5 / 2; 3.

More information

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice CONTENTS: Arrays Strings COMP-202 Unit 5: Loops in Practice Computing the mean of several numbers Suppose we want to write a program which asks the user to enter several numbers and then computes the average

More information

Java is an objet-oriented programming language providing features that support

Java is an objet-oriented programming language providing features that support Java Essentials CSCI 136: Spring 2018 Handout 2 February 2 Language Basics Java is an objet-oriented programming language providing features that support Data abstraction Code reuse Modular development

More information

Repetition, Looping. While Loop

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

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements Course Name: Advanced Java Lecture 3 Topics to be covered Control Statements Introduction The control statement are used to control the flow of execution of the program. This execution order depends on

More information

22c:111 Programming Language Concepts. Fall Types I

22c:111 Programming Language Concepts. Fall Types I 22c:111 Programming Language Concepts Fall 2008 Types I Copyright 2007-08, The McGraw-Hill Company and Cesare Tinelli. These notes were originally developed by Allen Tucker, Robert Noonan and modified

More information

Lecture 12. Data Types and Strings

Lecture 12. Data Types and Strings Lecture 12 Data Types and Strings Class v. Object A Class represents the generic description of a type. An Object represents a specific instance of the type. Video Game=>Class, WoW=>Instance Members of

More information

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true; Programming in C++ If Statements If the sun is shining Choice Statements if (the sun is shining) go to the beach; True Beach False Class go to class; End If 2 1 Boolean Data Type (false, ) i.e. bool bflag;

More information

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof. GridLang: Grid Based Game Development Language Language Reference Manual Programming Language and Translators - Spring 2017 Prof. Stephen Edwards Akshay Nagpal Dhruv Shekhawat Parth Panchmatia Sagar Damani

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

More information

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

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops 1.3 Conditionals and Loops any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

AP Programming - Chapter 6 Lecture

AP Programming - Chapter 6 Lecture page 1 of 21 The while Statement, Types of Loops, Looping Subtasks, Nested Loops I. The while Statement Note: Loop - a control structure that causes a sequence of statement(s) to be executed repeatedly.

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Following is the general form of a typical decision making structure found in most of the programming languages:

Following is the general form of a typical decision making structure found in most of the programming languages: Decision Making Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

Mul$dimensional arrays. CSCI 136: Fundamentals of Computer Science II Keith Vertanen

Mul$dimensional arrays. CSCI 136: Fundamentals of Computer Science II Keith Vertanen Mul$dimensional arrays CSCI 136: Fundamentals of Computer Science II Keith Vertanen Overview Mul,dimensional arrays An array of arrays 2D arrays = a grid of variables Ragged arrays Higher dimensional arrays

More information

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

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,

More information

1.3 Conditionals and Loops

1.3 Conditionals and Loops .3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2008 February 04, 2008 0:00 AM A Foundation for Programming A Foundation

More information

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours: CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Tuesday 10:00 AM 12:00 PM * Wednesday 4:00 PM 5:00 PM Friday 11:00 AM 12:00 PM OR

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

Mul$- state systems CSCI 255: Introduc/on to Embedded Systems Keith Vertanen Copyright 2011

Mul$- state systems CSCI 255: Introduc/on to Embedded Systems Keith Vertanen Copyright 2011 Mul$- state systems CSCI 255: Introduc/on to Embedded Systems Keith Vertanen Copyright 2011 Overview Avoiding magic numbers Variables takes on a small set of values Use descrip:ve names instead of literal

More information

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

More information

STUDENT LESSON A12 Iterations

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

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

More information

CHAPTER : 9 FLOW OF CONTROL

CHAPTER : 9 FLOW OF CONTROL CHAPTER 9 FLOW OF CONTROL Statements-Statements are the instructions given to the Computer to perform any kind of action. Null Statement-A null statement is useful in those case where syntax of the language

More information

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming (Spring 2012) Lecture #5: Conditionals and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements:

More information

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly. 2.3 Recursion Overview Mathematical Induction What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations

More information

CHAPTER 5 FLOW OF CONTROL

CHAPTER 5 FLOW OF CONTROL CHAPTER 5 FLOW OF CONTROL PROGRAMMING CONSTRUCTS - In a program, statements may be executed sequentially, selectively or iteratively. - Every programming language provides constructs to support sequence,

More information

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View 1/16/12 A Foundation for Programming CS 112 Introduction to Programming (Spring 2012) any program you might want to write Lecture #4: Built-in Types of Data objects Zhong Shao methods and classes graphics,

More information

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Loops and Files Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Chapter Topics o The Increment and Decrement Operators o The while Loop o Shorthand Assignment Operators o The do-while

More information

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

More information

CONDITIONAL EXECUTION

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

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

What did we talk about last time? Examples switch statements

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 information

Zheng-Liang Lu Java Programming 45 / 79

Zheng-Liang Lu Java Programming 45 / 79 1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 45 / 79 Example Given a radius

More information

Chapter 7. Iteration. 7.1 Multiple assignment

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

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

Topic 4 Expressions and variables

Topic 4 Expressions and variables Topic 4 Expressions and variables "Once a person has understood the way variables are used in programming, he has understood the quintessence of programming." -Professor Edsger W. Dijkstra Based on slides

More information

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Computer Programming, I. Laboratory Manual. Experiment #3. Selections 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 #3

More information

FORM 2 (Please put your name and form # on the scantron!!!!)

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam 2: FORM 2 (Please put your name and form # on the scantron!!!!) True (A)/False(B) (2 pts each): 1. Recursive algorithms tend to be less efficient than iterative algorithms. 2. A recursive function

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

About Codefrux While the current trends around the world are based on the internet, mobile and its applications, we try to make the most out of it. As for us, we are a well established IT professionals

More information

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types. Class #07: Java Primitives Software Design I (CS 120): M. Allen, 13 Sep. 2018 Two Types of Types So far, we have mainly been dealing with objects, like DrawingGizmo, Window, Triangle, that are: 1. Specified

More information