1 gentle introduction to programming session 2: functions

42
1 Gentle Introduction to Programming Session 2: Functions

Post on 20-Dec-2015

228 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 1 Gentle Introduction to Programming Session 2: Functions

1

Gentle Introduction to Programming

Session 2: Functions

Page 2: 1 Gentle Introduction to Programming Session 2: Functions

2

Admin• Upcoming Sunday: practical session @ Schreiber Computer lab #4, 9-11, 11-13• Scala / Eclipse installation status?

Page 3: 1 Gentle Introduction to Programming Session 2: Functions

3

Review• General terms in CS & programming• Scala

• variables & types• operators• if / while

• Compiler / Interpreter• Eclipse / Scala shell• Ohad’s talk

Page 4: 1 Gentle Introduction to Programming Session 2: Functions

4

Today• More Scala:

• loops• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style

• Guest lecture by Oded Magger (10:10)• Home work review• Functions• Home work

Page 5: 1 Gentle Introduction to Programming Session 2: Functions

5

Loops

• Used to repeat the same instructions until a stop criterion is met

• for, while loops:• while (<condition>)

<statement>• for (<range and update>)

<statement>

Page 6: 1 Gentle Introduction to Programming Session 2: Functions

6

Example - while

// factorialprintln(“Enter a non-negative number”)var n : Int = Console.readInt()

var fact : Int = 1var i : Int = 1

while (i <= n) {fact = fact * ii = i + 1

}println(n + “! = “ + fact)

Page 7: 1 Gentle Introduction to Programming Session 2: Functions

7

Example - for

// factorialprintln(“Enter a non-negative number”)var n : Int = Console.readInt()

var fact : Int = 1

for (i <- 1 to n) {fact = fact * i

}println(“n! = “ + fact)

Page 8: 1 Gentle Introduction to Programming Session 2: Functions

8

Examples at Factorial.scala

Page 9: 1 Gentle Introduction to Programming Session 2: Functions

9

Example - Prime

// Find whether a number is a primeprintln(“Enter a non-negative number”)var n : Int = Console.readInt()

var j : Int = 2var stop : Boolean = falsewhile ((j <= n/2) && !stop) {

stop = (n%j == 0) j = j + 1

}if (!stop) {

println(n)} Prime.scala

Page 10: 1 Gentle Introduction to Programming Session 2: Functions

10

When to use for/while?

• Some applications are more natural to for, and others to while

• for is more suited when something is performed a predefined number of times, or when iterating over a list of objects

• while is more suited if the number of iterations is not known in advance (e.g., asking for legal input from a user)

Page 11: 1 Gentle Introduction to Programming Session 2: Functions

11

Infinite Loops

• What are they?

• Beware of them

Page 12: 1 Gentle Introduction to Programming Session 2: Functions

12

Scala’s Control Strctures

• All of Scala’s control structures result in some value:

• Example:

println(if (price > 100) “expensive” else “cheap”)

Page 13: 1 Gentle Introduction to Programming Session 2: Functions

13

Var versus Val

• val – “final” variable / imutable• Example:

Page 14: 1 Gentle Introduction to Programming Session 2: Functions

14

Strings• val s : String = “ABC”• A sequence of characters• Have additional functionality (expressed by methods)

Page 15: 1 Gentle Introduction to Programming Session 2: Functions

15

Application Programming Interface (API)

• How could I know that String has a method toLowerCase? • How about checking the Scala API? http://www.scala-lang.org/docu/files/api/index.html • Oops…

Page 16: 1 Gentle Introduction to Programming Session 2: Functions

16

Java and Scala

• Scala is fully compatible with Java• Actually, Scala is compiled into Java Bytecode• And here is the String API (finally…) http://download-llnw.oracle.com/javase/6/docs/api/java/lang/String.html

Page 17: 1 Gentle Introduction to Programming Session 2: Functions

17

Type Inference

Scala’s ability to figure out types you leave off

Page 18: 1 Gentle Introduction to Programming Session 2: Functions

18

Variable Scope

output

MultiTable.scala

Page 19: 1 Gentle Introduction to Programming Session 2: Functions

19

Programming Style

• Comments: //, /* */

• Indentation (cntl + i in eclipse)

• Meaningful variables names

Why is it important?

Page 20: 1 Gentle Introduction to Programming Session 2: Functions

20

Today• More Scala:

• loops• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style

• Guest lecture by Oded Magger (10:10)• Home work review• Functions• Home work

Page 21: 1 Gentle Introduction to Programming Session 2: Functions

21

Exercise 0

• Write your first “Hello World!” program in Scala:• Use the interpreter• In Eclipse

• Make sure it compiles and executes properly• Congratulations!

Do you want u

s to do it

together?

Hello.scala

Page 22: 1 Gentle Introduction to Programming Session 2: Functions

22

Fibonacci

• Fibonacci series0, 1, 1, 2, 3, 5, 8, 13, 21, 34• Definition:

• fib(0) = 0• fib(1) = 1• fib(n) = fib(n-1) + fib(n-2)

en.wikipedia.org/wiki/Fibonacci_number

Page 23: 1 Gentle Introduction to Programming Session 2: Functions

23

Exercise 1

• Write a program that receives from the user an integer n > 0 and prints to the screen the n th Fibonacci number.

a. Use a “while” loopb. Use a “for” loop

Page 24: 1 Gentle Introduction to Programming Session 2: Functions

24

Solution

?

Fibonacci.scala

Page 25: 1 Gentle Introduction to Programming Session 2: Functions

25

Command Line Arguments In Eclipse

Page 26: 1 Gentle Introduction to Programming Session 2: Functions

26

Command Line Arguments In Eclipse

Page 27: 1 Gentle Introduction to Programming Session 2: Functions

27

Functions

• A group of declarations and statements that is assigned a name • Effectively, a named statement block • Usually has a value

• A sub-program

• When we write our program we always define a function named main

• Inside main we can call other functions • Which can themselves use other functions, and so on…

Page 28: 1 Gentle Introduction to Programming Session 2: Functions

28

Today• More Scala:

• loops• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style

• Guest lecture by Oded Magger (10:10)• Home work review• Functions• Home work

Page 29: 1 Gentle Introduction to Programming Session 2: Functions

29

What are They Good For?

• Generalize a repeated set of instructions • We don’t have to keep writing the same thing over and

over• Solve bugs once…

• They can break your problem down into smaller sub-tasks • Easier to solve complex problems

• They make a program much easier to read and maintain• Abstraction – we don’t have to know how a function is

implemented to use it

Page 30: 1 Gentle Introduction to Programming Session 2: Functions

30

In Short• Why do we need functions?

• Code reusability• Modularity• Abstraction

Page 31: 1 Gentle Introduction to Programming Session 2: Functions

31

Function Definition in Scala

Page 32: 1 Gentle Introduction to Programming Session 2: Functions

32

Example

Page 33: 1 Gentle Introduction to Programming Session 2: Functions

33

Example

Page 34: 1 Gentle Introduction to Programming Session 2: Functions

34

Function Output

• The last statement defines returned value to the calling function

• The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)

• If no value is to be returned, the return-type of the function should be set to ‘Unit’, and a unit value is returned

Page 35: 1 Gentle Introduction to Programming Session 2: Functions

35

Other Types of Functions

• Method – member of some object (e.g., String – toLowerCase)

• Local functions: functions nested within functions

• Function literals (First-class functions), e.g: (x:Int) => x+1

• Why do we need it anyway?

• Function values (e.g., val f = (x:Int => x+1))

Page 36: 1 Gentle Introduction to Programming Session 2: Functions

36

Example: Nested

Functions

PrimesNested.Scala

Page 37: 1 Gentle Introduction to Programming Session 2: Functions

37

There are many ways to define functions in Scala

FuncDef.scala

Page 38: 1 Gentle Introduction to Programming Session 2: Functions

38

Example

((x : Int) => x * 2)(a)

((x : Int) => x * 2)(5)

((x : Int) => x * 2)5 5

10

Page 39: 1 Gentle Introduction to Programming Session 2: Functions

39

Today• More Scala:

• loops• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style

• Guest lecture by Oded Magger (10:10)• Home work review• Functions• Home work

Page 40: 1 Gentle Introduction to Programming Session 2: Functions

40

Exercise – Integer Division

• Input:• Two integers – A and B

• Output:• How many times A contains B (it is the result of

the integer division A/B)

• Do not use the operators ‘/’, ‘*’

• Solution:

Page 41: 1 Gentle Introduction to Programming Session 2: Functions

41

Exercise – Power of Two

• Input: integer A

• Output: is there an integer N such that A == 2^N?

• Solution:

Page 42: 1 Gentle Introduction to Programming Session 2: Functions

42

Write a program that prints an upside-down half triangle of *.

The height of the pyramid is the input.

*****

*****

****

*

Exercise – Triangle Printout