DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Similar documents
DM503 Programming B. Peter Schneider-Kamp.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM502 Programming A. Peter Schneider-Kamp.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM503 Programming B. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM536 Introduction to Programming. Peter Schneider-Kamp.

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

DM536 Introduction to Programming. Peter Schneider-Kamp.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Introduction to Programming Using Java (98-388)

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Loops. CSE 114, Computer Science 1 Stony Brook University

CS 231 Data Structures and Algorithms, Fall 2016

DM502 Programming A. Peter Schneider-Kamp.

DM536 / DM550 Part 1 Introduction to Programming. Peter Schneider-Kamp.

AP CS Unit 3: Control Structures Notes

Introduction to Computer Science Unit 2. Notes

More Control Structures

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

1.00 Lecture 5. Floating Point Anomalies

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

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

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

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

Introduction to Computer Science Unit 2. Notes

3. Java - Language Constructs I

CSC Java Programming, Fall Java Data Types and Control Constructs

Java Simple Data Types

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

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

Java Simple Data Types

CONDITIONAL EXECUTION

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

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

AP COMPUTER SCIENCE A

Java Identifiers, Data Types & Variables

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

Java Basic Programming Constructs

More types, Methods, Conditionals. ARCS Lab.

CS115 Principles of Computer Science

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

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

THE CONCEPT OF OBJECT

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Building Java Programs

Chapter 4: Control Structures I

Prof. Navrati Saxena TA: Rochak Sachan

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

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

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Loops and Expression Types

JAVA OPERATORS GENERAL

Java Programming. Atul Prakash

CS171:Introduction to Computer Science II

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

Lara Technologies Special-Six Test

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

SOFTWARE DEVELOPMENT 1. Control Structures 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Java Programming: from the Beginning. Chapter 8 More Control Structures. CSc 2310: Principle of Programming g( (Java) Spring 2013

Important Java terminology

Lecture 14. 'for' loops and Arrays

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Key Java Simple Data Types

Arithmetic Compound Assignment Operators

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

PROGRAMMING FUNDAMENTALS

Programming Basics. Digital Urban Visualization. People as Flows. ia

Eng. Mohammed S. Abdualal

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

UNIT II Structuring the Data, Computations and Program. Kainjan Sanghavi

1.3 Conditionals and Loops

Course Outline. Introduction to java

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

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

Java for Non Majors Spring 2018

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

CSC 1214: Object-Oriented Programming

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

IEEE Floating-Point Representation 1

AP Computer Science Unit 1. Programs

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

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

Research Group. 2: More types, Methods, Conditionals

n Group of statements that are executed repeatedly while some condition remains true

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

Java Tutorial. Saarland University. Ashkan Taslimi. Tutorial 3 September 6, 2011

Chapter 4: Conditionals and Recursion

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Transcription:

DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/

CALLING & DEFINING FUNCTIONS 2

Functions and Methods all functions in java are defined inside a class BUT static functions are not associated with one object a static function belongs to the class it is defined in functions of a class called by <class>.<function>(<args>) Example: Math.pow(2, 6) all other (i.e. non-static) functions belong to an object in other words, all non-static functions are methods! functions of an object called by <object>.<function>(<args>) Example: String s1 = "Hello!"; System.out.println(s1.toUpperCase()); 3

Calling Functions & Returning Values function calls are expressions exactly like in Python Example: int x = sc.nextint(); argument passing works exactly like in Python Example: System.out.println(Math.log(Math.E)) the return statement works exactly like in Python Example: return Math.sqrt(a*a+b*b); 4

Function Definitions functions are defined using the following grammar rule: <func.def> => static <type> <function>(, <type i > <arg i >, ) { <instr 1 >; ; <instr k >; Example (static function): public class Pythagoras { static double pythagoras(double a, double b) { return Math.sqrt(a*a+b*b); public static void main(string[] args) { System.out.println(pythagoras(3, 4)); 5

Method Definitions methods are defined using the following grammar rule: <meth.def> => <type> <function>(, <type i > <arg i >, ) { <instr 1 >; ; <instr k >; Example (method): public class Pythagoras { double a, b; Pythagoras(double a, double b) { this.a = a; this.b = b; double compute() { return Math.sqrt(this.a*this.a+this.b*this.b); public static void main(string[] args) { Pythagoras pyt = new Pythagoras(3, 4); System.out.println(pyt.compute()); constructor corresponds to init (self, a, b) 6

Stack Diagrams Pythagoras.main pyt è Pythagoras(3, 4) pyt.compute this Math.sqrt x è 25 7

SIMPLE ITERATION 8

Iterating with While Loops iteration = repetition of code blocks while statement: <while-loop> => while (<cond>) { <instr 1 >; <instr 2 >; <instr 3 >; Example: static void countdown(int n) { while (n > 0) { false true n == 3 2 1 0 System.out.println(n); n--; System.out.println("Ka-Boom!"); 9

Breaking a Loop sometimes you want to force termination Example: while (true) { System.out.println("enter a number (or 'exit'):\n"); String num = sc.nextline(); if (num.equals("exit")) { break; int n = Integer.parseInt(num); System.out.println("Square of "+n+" is: "+n*n); System.out.println("Thanks a lot!"); 10

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) for square root of a: f(x) = x 2 a f (x) = 2x simplifying for this special case: x n+1 = (x n + a / x n ) / 2 Example: double xn = 1; while (true) { System.out.println(xn); double xnp1 = (xn + a / xn) / 2; if (xnp1 == xn) { break; xn = xnp1; 11

Approximating Square Roots Newton s method for finding root of a function f: 1. start with some value x 0 2. refine this value using x n+1 = x n f(x n ) / f (x n ) for square root of a: f(x) = x 2 a f (x) = 2x simplifying for this special case: x n+1 = (x n + a / x n ) / 2 Example: double xnp1 = 1; do { xn = xnp1; System.out.println(xn); double xnp1 = (xn + a / xn) / 2; while (xnp1!= xn); 12

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Execution: 1. initialize counter variable using <init> 2. check whether condition <cond> holds 3. if not, END the for loop 4. if it holds, first execute <instr 1 > <instr k > 5. then execute <update> 6. jump to Step 2 13

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { System.out.println(n); n--; System.out.println("Ka-Boom!"); 14

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { for (int n = 10; n > 0; n--) { System.out.println(n); n--; System.out.println("Boo!"); 15

Iterating with For Loops (standard) for loops very different from Python grammar rule: <for-loop> => for (<init>; <cond>; <update>) { <instr 1 >; ; <instr k >; Example: int n = 10; while (n > 0) { for (int n = 10; n > 0; n--) { System.out.println(n); System.out.println(n); n--; System.out.println("Boo!"); System.out.println("Boo!"); 16

CONDITIONAL EXECUTION 17

Conditional Execution the if-then statement executes code only if a condition holds grammar rule: <if-then> => if (<cond>) { <instr 1 >; ; <instr k >; Example: if (x <= 42) { System.out.println("not more than the answer"); if (x > 42) { System.out.println("sorry - too much!"); 18

Control Flow Graph Example: if (x <= 42) { System.out.println("A"); if (x > 42) { System.out.println("B"); x <= 42 false x > 42 false true true System.out.println("A"); System.out.println("B"); 19

Alternative Execution the if-then-else statement executes one of two code blocks grammar rule: <if-then-else> => if (<cond>) { <instr 1 >; ; <instr k >; else { <instr 1 >; ; <instr k >; Example: if (x <= 42) { System.out.println("not more than the answer"); else { System.out.println("sorry - too much!"); 20

Control Flow Graph Example: if (x <= 42) { System.out.println("A"); else { System.out.println("B"); x <= 42 false true print "A" print "B" 21

Chained Conditionals alternative execution a special case of chained conditionals grammar rules: <if-chained> => if (<cond 1 >) { <instr 1,1 >; ; <instr k1,1 >; else if (<cond 2 >) { else { <instr 1,m >; ; <instr km,m >; Example: if (x > 0) { System.out.println("positive"); else if (x < 0) { System.out.println("negative"); else { System.out.println("zero"); 22

Control Flow Diagram Example: if (x > 0) { System.out.println("A"); else if (x < 0) { System.out.println("B"); else { System.out.println("C"); false x > 0 x < 0 true true false print "positive" print "negative" print "zero" 23

Switch Statement for int and char, special statement for multiple conditions grammar rules: <switch> => switch (<expr>) { case <const 1 >: <instr 1,1 >; ; <instr k1,1 >; break; case <const 2 >: default: <instr 1,m >; ; <instr km,m >; 24

Switch Statement Example: int n = sc.nextint(); switch (n) { case 0: System.out.println("zero"); break; case 1: case 2: System.out.println("smaller than three"); default: System.out.println("negative or larger than two"); 25

Nested Conditionals conditionals can be nested below conditionals: if (x > 0) { if (y > 0) { System.out.println("Quadrant 1"); else if (y < 0) { System.out.println("Quadrant 4"); else { System.out.println("positive x-axis"); else if (x < 0) { if (y > 0) { System.out.println("Quadrant 2"); else if (y < 0) { System.out.println("Quadrant 3"); else { System.out.println("negative x-axis"); else { System.out.println("y-Axis"); 26

TYPE CASTS & EXCEPTION HANDLING 27

Type Conversion Java uses type casts for converting values (int) x: converts x into an integer Example 1: ((int) 127) + 1 == 128 Example 2: (int) -3.999 == -3 (double) x: converts x into a float Example 1: (double) 42 == 42.0 Example 2: (double) "42" results in Compilation Error (String) x: views x as a string Example: Object o = "Hello World! ; String s = (String) o; 28

Catching Exceptions type conversion operations are error-prone Example: Object o = new Integer(23); Strings s = (String) o; good idea to avoid type casts sometimes necessary, e.g. when implementing equals method use try-catch statement to handle error situations Example 1: String s; try { s = (String) o; catch (ClassCastException e) { s = "ERROR"; 29

Catching Exceptions use try-catch statement to handle error situations Example 2: try { double x; x = Double.parseDouble(str); System.out.println("The number is " + x); catch (NumberFormatException e) { System.out.println("The number sucks."); 30

Arrays array = built-in, mutable list of fixed-length type declared by adding [] to base type Example: int[] speeddial; creation using same new as for objects size declared when creating array Example: speeddial = new int[20]; also possible to fill array using { while creating it then length determined by number of filled elements Example: speeddial = {65502327, 55555555; 31