• No results found

mathematical functions + Functions

N/A
N/A
Protected

Academic year: 2022

Share "mathematical functions + Functions"

Copied!
85
0
0

Loading.... (view fulltext now)

Full text

(1)

CS 101:

Computer Programming and Utilization

Puru

with

CS101 TAs and Staff

Course webpage: https://www.cse.iitb.ac.in/~cs101/

Lecture 11: How computers work? + Common

mathematical functions + Functions

(2)

Autumn 2019 CS101@CSE IIT Bombay

outline

• how computers work? (recap)

• examples of mathematical functions (howework)

functions (slide 43)

2

(3)

recap

• Numbering systems

– decimal, binary, hexadecimal

• Number representation

– two’s complement (for integers)

– mantissa/significand + exponent form (for float/double)

How computers work?

(4)

Autumn 2019 CS101@CSE IIT Bombay

The Hardware

(A very high level glimpse)

How do we store numbers in hardware?

How is an instruction expressed in hardware?

How is it executed?

How do we output the numbers?

4

(5)

representing numbers

Example: 25 Decimal = 11001 binary

Use 5 capacitors

Store high charge on 1st, 2nd, 5th, and low charge on 3rd, 4th

To transmit 25 from one part of the computer to another

Use 5 wires and raise the wires to appropriate voltages at one end.

Sense the voltages at the other end

Key idea:

store each bit of the number on a

separate capacitor

(6)

Autumn 2019 CS101@CSE IIT Bombay

organization of a computer

6

(7)

memory

• Organized into bytes (groups of 8 capacitors)

• Memories of present day computers contain few Gigabytes, Giga=2

30

• Each byte in the memory is assigned a distinct number, or an address

• In a memory with N bytes, the addresses go from 0 to N-1

0 0 0 0 1 1 0 1 0 1

2 3 4

5 1 0 1 1 1 1 0 1 6

7 8 9

(8)

Autumn 2019 CS101@CSE IIT Bombay

memory ports

• Memory has 3 ports: address port, data port, control port.

• Address port consists of log N wires.

(N = number of bytes in memory)

• You can place numbers 0..N-1 on address port

• Control Port may be just 1 wire.

Wire = 0: Memory to perform read operation.

Wire = 1: Memory to perform write operation.

• Data port will have w wires, where w is a multiple of 8. Say w=8m.

8

(9)

write operation

0 1

10010

11101000

"Write the number 11101000 (232) into the location number

(10)

Autumn 2019 CS101@CSE IIT Bombay

read operation

1

10010

11101000

"Read from the location number 10010 (18)

0

10

(11)

arithmetic unit

• Ports: Input1, Input2, Output, Control

• Typically Input1, Input2, Output will consist of w wires, w = size of memory data port

• Control = several wires. Number appearing on the control

wires will say what operation should be performed

(12)

Autumn 2019 CS101@CSE IIT Bombay

peripherals: keyboard, screen, disk…

• Also have control port and data port like

organization.

• Depending upon value placed on control port, the peripheral decides what to do with the

value on the data port, or itself places values on the data port.

data

control data control

control data

12

(13)

control unit

• Tells other parts of the computer what to do.

– Sends numbers on control wires of each unit

• The control unit decides what to tell other units by reading a “machine language

program” from the memory of the

computer.

(14)

Autumn 2019 CS101@CSE IIT Bombay

machine language program

OPCODE OPERAND1 OPERAND2 OPERAND3

• Program = Sequence of instructions

• Instruction = sequence of numbers

– First number is OPERATION CODE (OPCODE). This is the

code that tells the Control Unit what OPERATION should do.

– Subsequent numbers are OPERANDS. These are

"arguments" to the operation

• i386

• x86_64

• PowerPC

14

(15)

example

57 100 200 300

• operation code 57 might mean:

– interpret the 3 numbers following 57 as addresses.

– read the words at the first two addresses and send them to the Arithmetic unit.

– command the arithmetic unit to perform multiplication by sending appropriate number on its control wires.

– store the result from the arithmetic unit into the word at the third address

• operation codes are defined by the computer designer

She will assign a different code for each operation that she would like the computer to perform.

Example: 58 might mean the same thing as above, except that the numbers would be added.

(16)

Autumn 2019 CS101@CSE IIT Bombay

control unit operation

• Control unit must be told where the machine language program is in memory

• The control unit then fetches the instructions constituting the program, interprets the codes, and performs the required operation

• After one instruction is fetched and executed, it fetches the next instruction and repeats the

process

16

(17)

putting it together

Memory

Arthimetic Unit

Control Unit Bus (network) 0

1 ..

10 ...

100 ....

200 ...

300

57 100 200 300

10

1. Control unit is told the address of the instruction to fetch (e.g. instruction is at location 10)

2. A read operation is performed on memory location 10 3. instruction

57 100 200 300

is now "loaded" into the control unit

57 100 200 300 289

345

Read Write

1 0

(18)

Autumn 2019 CS101@CSE IIT Bombay

putting it together

Memory

Arthimetic Unit

Control Unit Bus (network) 0

1 ..

10 ...

100 ....

200 ...

300

57 100 200 300

100

1. Now control unit performs a read

operation of address 100

2. The number 289 is sent to input 1 of arithmetic unit

289 289

345

Read Write

1 0

18

(19)

putting it together

Memory

Arthimetic Unit

Control Unit Bus (network) 0

1 ..

10 ...

100 ....

200 ...

300

57 100 200 300

200

1. Now control unit performs a read

operation of address 200

2. The number 345 is sent to input 2 of arithmetic unit

345 289

345

Read Write

1 0

(20)

Autumn 2019 CS101@CSE IIT Bombay

putting it together

Memory

Arthimetic Unit

Control Unit Bus (network) 0

1 ..

10 ...

100 ....

200 ...

300

57 100 200 300

1. Now control unit instructs the

arithmetic unit to perform a multiply operation (the

"control" wires are set to the operation code of "multiply") 2. Control unit

stores the product (289 x 345 = 99705) temporarily inside its own unit

289 345

Read Write

0 0

x

x

99705

99705

20

(21)

putting it together

Memory

Arthimetic Unit

Control Unit Bus (network) 0

1 ..

10 ...

100 ....

200 ...

300

57 100 200 300

300

1. Now control unit performs a write operation on address 300 2. The number

99705 is sent on the data port of memory and 300 is sent on the address port of the memory

99705 289

345

Read Write

0 1

Instruction

execution is COMPLETE

99705

(22)

Autumn 2019 CS101@CSE IIT Bombay

Common Mathematical

Functions

(23)

mathematical functions & loops

Chapter 8

An Introduction to Programming Through C++

by Abhiram Ranade (Tata McGraw Hill, 2014)

– McLaurin Series (to calculate function values) – Numerical Integration

– Bisection Method

– Newton-Raphson Method

(24)

Autumn 2019 CS101@CSE IIT Bombay

1. MacLaurin series

• When x is close to 0:

– f(x) = f(0) + f'(0)x + f''(0)x2 / 2! + f'''(0)x3 / 3! + …

• E.g. if f(x) = sin x

24

(25)

Maclaurin series

• When x is close to 0:

– f(x) = f(0) + f'(0)x + f''(0)x2 / 2! + f'''(0)x3 / 3! + …

• E.g. if f(x) = sin x

f(x) = sin(x), f(0) = 0 – f'(x) = cos(x), f'(0) = 1 – f''(x) = -sin(x), f''(0) = 0 – f'''(x) = -cos(x), f'''(0) = -1 – f''''(x) = sin(x), f''''(0) = 0

• The pattern repeats

(26)

Autumn 2019 CS101@CSE IIT Bombay

Maclaurin series example

• Thus, sin(x) = x – x

3

/3! + x

5

/5! – x

7

/7! …

– Madhava, Taylor, Maclaurin, Gregory, Leibniz

• A fairly accurate value of sin(x) can be obtained by using sufficiently many terms

• Error after taking k terms is is at most the absolute value of the k+1 term

26

(27)

Error for the sine function after 7 terms

(28)

Autumn 2019 CS101@CSE IIT Bombay

Program Plan-High Level

sin(x) = x – x

3

/3! + x

5

/5! – x

7

/7! …

Use the accumulation idiom Use a variable called term

This will keep taking successive values of the terms Use a variable called sum

Keep adding term into this variable

28

(29)

Program Plan: Details

sin(x) = x – x

3

/3! + x

5

/5! – x

7

/7! …

• sum can be initialized to the value of the first term

– so, sum = x

• Now we need to figure out initialization of term and it's update

• Can we represent the kth term from the (k-1) th term

(30)

Autumn 2019 CS101@CSE IIT Bombay

Program Plan: Terms

sin(x) = x – x

3

/3! + x

5

/5! – x

7

/7! …

Let t

k

= kth term of the series, k=1, 2, 3…

t

k

= (-1)

k+1

x

2k-1

/(2k-1)!

t

k-1

= (-1)

k

x

2k-3

/(2k-3)!

t

k

= (-1)

k

x

2k-3

/(2k-3)! * (-1)(x

2

)/((2k-2)(2k-1))

= - t

k-1

(x)

2

/((2k-2)(2k-1)

30

(31)

Program Plan

• Loop control variable will be k

• In each iteration we calculate t

k

from t

k-1

• The term t

k

is added to sum

• A variable term will keep track of t

k

– At the beginning of k

th

iteration, term will have the value t

k-1

, and at the end of k

th

iteration it will have the value t

k

• After k

th

iteration, sum will have the value = sum of the first k terms of the Taylor series

• Initialize sum = x, term = x

• In the first iteration of the loop we calculate the sum of 2 terms.

So initialize k = 2

• We stop the loop when term becomes small enough

(32)

Autumn 2019 CS101@CSE IIT Bombay

Program for the sin(x) Maclaurin series

main_program{

double x; cin >> x;

double epsilon = 1.0E-20; // very small number double sum = x, term = x;

for(int k=2; abs(term) > epsilon; k++){

term = term*(-x*x / ((2*k – 1)*(2*k – 2));

sum = sum + term;

}

cout << sum << endl;

}

32

(33)

2. Numerical Integration (General)

• Integral from p to q = area under curve

• Approximate area by rectangles

p q

f

(34)

Autumn 2019 CS101@CSE IIT Bombay

Plan (General)

• Read in p, q (assume p < q)

• Read in n = number of rectangles

• Calculate w = width of rectangle = (q-p)/n

• ith rectangle, i=0,1,…,n-1 begins at p+iw

• Height of ith rectangle = f(p+iw)

• Given the code for f, we can calculate height and width of each rectangle and so we can add up the areas

34

(35)

Example: Area of semi-circular disk

• Divide x-axis into intervals of width w

• Approximate area under

function f ( x ) between x and x + w as w x f(x)

• As w becomes smaller,

estimate should become more

accurate

(36)

Autumn 2019 CS101@CSE IIT Bombay

One loop nested in another

double w = .01;

for (; w > 1.0e-30; w/=2) {

// halve interval width

double area = 0; // for each width find area for (int x=-1.; x+w <=1.; x+=w) {

area += w * sqrt(1.0 – x*x);

}

cout << 2.0*area << endl;

}

36

(37)

Example: Numerical Integration to calculate ln(x)

Homework

Compare with in-built function log(x) ln(x) = natural logarithm

= ∫ 1/x dx from 1 to x

= area under the curve f(x)=1/x from 1 to x

(38)

Autumn 2019 CS101@CSE IIT Bombay

3. Bisection Method For Finding Roots

• Root of function f: Value x such that f(x)=0

• Many problems can be expressed as finding roots,

e.g. square root of w is the same as root of f(x) = x

2

– w

• Requirement:

− Need to be able to evaluate f

− f must be continuous

− We must be given points x

L

and x

R

such that f(x

L

) and f(x

R

) are not both positive or both negative

38

(39)

Bisection Method For Finding Roots

xL

xR xM

• Because of continuity, there must be a root between

(40)

Autumn 2019 CS101@CSE IIT Bombay

Bisection Method For Finding Roots

xL

xR xM

• Because of continuity, there must be a root between xL and xR (both inclusive)

• Let xM = (xL + xR)/2 = midpoint of interval (xL, xR)

• If f(xM) has same sign as f(xL), then f(xM), f(xR) have different signs

So we can set xL = xM and repeat

• Similarly if f(xM) has same sign as f(xR)

• In each iteration, xL, xR are coming closer

• When they come closer than certain epsilon, we can declare xL as the root

40

(41)

Bisection Method For Finding Square Root of 2

• Same as finding the root of x

2

- 2 = 0

• Need to support both scenarios:

− xL is negative, xR is positive

− xL is positive, xR is negative

• We have to check if xM has the

same sign as xL or xR

(42)

Autumn 2019 CS101@CSE IIT Bombay

other examples/techniques

• generalized square root f(x)=x

2

-y

• Newton Raphson method for root finding

42

(43)

Bisection Method for Finding √2

double xL=0, xR=2, xM, epsilon=1.0E-20;

// Invariant: xL < xR

while(xR – xL >= epsilon){ // Interval is still large xM = (xL+xR)/2; // Find the middle point bool xMisNeg = (xM*xM – 2) < 0;

if(xMisNeg) // xM is on the side of xL xL = xM;

else xR = xM; // xM is on the side of xR // Invariants continues to remain true

}

cout << xL << endl;

(44)

Autumn 2019 CS101@CSE IIT Bombay

Functions

(45)

Functions

• Based on Chapter 9 of the book

An Introduction to Programming Through C++

by Abhiram Ranade (Tata McGraw Hill, 2014)

(46)

Autumn 2019 CS101@CSE IIT Bombay

can we define new commands?

• have we seen commands other than C++ syntax/commands?

46

(47)

can we define new commands?

• we already have many commands, e.g

− sqrt(x) evaluates to the square root of x

− forward(d) moves the turtle forward d pixels

• can we define new commands?

− gcd(m,n) should evaluate to the GCD of m,n

− dash(d) should move the turtle forward, but draw dashes as it moves rather than a continuous line

Function: official name for command that performs some work

when invoked

(48)

Autumn 2019 CS101@CSE IIT Bombay

Functions

• Examples of defining and using functions

• How to define a function in general

• How a function executes

• Contract view of functions

• Passing parameters by reference

48

(49)

why functions?

• write a program that prints the GCD of 36, 24, and of 99, 47

(50)

Autumn 2019 CS101@CSE IIT Bombay

why functions?

main_program{

int m=36, n=24;

while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

cout << n << endl;

m=99; n=47;

while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

cout << n << endl;

}

• Write a program that prints the GCD of 36, 24, and of 99, 47

• Using what you already know:

– Make 2 copies of code to find GCD.

Use the first copy to find the GCD of 36, 24 Use the second copy to find the

GCD of 99, 47

• Duplicating code is not good

– May make mistakes in copying.

– What if we need the GCD at 10 places in the program?

– This is inelegant. Ideally, you should not have to state anything more than once

REUSE!

50

(51)

Using a function

int gcd(int m, int n){

while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

return n;

}

main_program{

int a=36,b=24, c=47;

cout <<gcd(a,b) << endl;

cout <<gcd(99,c)<< endl;

}

A complete program

= function definitions + main program

Function definition:

information about function name

how it is to be called what it computes what it returns

Main program:

calls or invokes functions gcd(a,b) : call/invocation gcd(99,c) : another call

Values supplied for each call:

arguments or parameters to the

call

(52)

Autumn 2019 CS101@CSE IIT Bombay

Form of Function Definitions

return-type name-of-function (parameter1-type parameter1-name, parameter2-type parameter2-name, …)

{ function-body }

• return-type: the type of the value returned by the function, e.g. int returned by gcd function ealier

Some functions may not return anything

• name-of-function: e.g. gcd

• parameter: variables that to hold the values of the arguments to the function.

m, n in gcd

• function-body: code that will get executed

52

(53)

Function execution

int gcd(int m, int n) { while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

return n;

}

main_program{

int a=36,b=24;

cout << gcd(a,b) << endl;

cout << gcd(99,47)<< endl;

}

• Each function has a separate data space (independent

scope)

• These data spaces are

arranged in a data structure called stack

• Imagine the data spaces as data books and stacked up one on the other

• The book on the top of the

stack is the one we can access

Last-In-First-Out (LIFO)

(54)

Autumn 2019 CS101@CSE IIT Bombay

Function execution

• Data space of a function is also called an activation frame (or activation record)

int gcd(int m, int n) { while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

return n;

}

main_program{

int a=36,b=24;

cout << gcd(a,b) << endl;

cout << gcd(99,47)<<

endl;

}

copy n back

copy values of aand b

into mand n storenin a return value area

54

(55)

(contd.)

• Execution of the called function ends when return statement is encountered

• Value following the keyword return is copied back to the calling program, to be used in place of the expression gcd(…,…)

• Activation frame of function is destroyed, i.e. memory reserved for it is taken back

• main_program resumes execution

(56)

Autumn 2019 CS101@CSE IIT Bombay

Function execution

• Activation frame: area in memory where function variables are stored

int gcd(int m, int n) { while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

return n;

}

main_program{

int a=36,b=24;

cout << gcd(a,b) << endl;

cout << gcd(99,47)<< endl;

}

gcd activation frame is destroyed

56

(57)

Function Execution

int gcd(int m, int n) { while(m % n != 0){

int r = m%n;

m = n;

n = r;

}

return n;

}

main_program{

int a=36,b=24;

cout << gcd(a,b) << endl;

cout << gcd(99,47)<< endl;

}

(58)

Autumn 2019 CS101@CSE IIT Bombay

Function execution details

1. main_program executes and reaches gcd(36,24) 2. main_program suspends

3. Preparations made to run subprogram gcd:

• Area allocated in memory where gcd will have its variables è activation frame of gcd

• Variables corresponding to parameters are created in activation frame

• Values of arguments are copied from activation frame of main_program to that of gcd.

This is termed passing arguments by value 4. Execution of function-body starts

58

(59)

Remarks

• Set of variables in calling program e.g. main_program is completely disjoint from the set in called function, e.g. gcd

• Both may contain same name.

Calling program will reference the variables in its activation frame, and called program in its activation frame

• New variables can be created in called function

• Arguments to calls/invocations can be expressions, which are first evaluated before called function executes

• Functions can be called while executing functions

A declaration of function must appear before its call

(60)

Autumn 2019 CS101@CSE IIT Bombay

function to compute LCM

• We can compute the least common multiple of two numbers m, n using a function

lcm(m,n)

60

(61)

function to compute LCM

• We can compute the least common multiple of two numbers m, n using the identity

• LCM(m,n) = m*n/GCD(m,n)

int lcm(int m, int n){

return m*n/gcd(m,n);

}

• lcm calls gcd.

(62)

Autumn 2019 CS101@CSE IIT Bombay

Program To Find LCM Using Functions gcd, lcm

int gcd(int m, int n) { …}

int lcm(int m, int n) {

return m*n/gcd(m,n);

}

main_program{

cout << lcm(50,75);

}

Function definitions appear before their calls

62

(63)

Program To Find LCM Using Functions gcd, lcm

int gcd(int m, int n) { …}

int lcm(int m, int n) {

return m*n/gcd(m,n);

}

main_program{

cout << lcm(50,75);

}

int gcd(int m, int n);

int lcm(int m, int n);

main_program{

cout << lcm(50,75);

cout << gcd(50,75);

}

int gcd(int m, int n) { …}

int lcm(int m, int n) {

return m*n/gcd(m,n);

Function definitions appear before their calls

Function declarations appear

before their calls and definitions

after their calls

(64)

Autumn 2019 CS101@CSE IIT Bombay

execution details

• main_program starts executing

• main_program suspends when the call lcm(..) is encountered

• Activation frame created for lcm

• lcm starts executing after 50, 75 copied to m,n call to gcd encountered. lcm suspends

• Activation frame created for gcd

• Execution of gcd starts after copying arguments 50, 75 to m,n of gcd.

• gcd executes. Will returns 25 as result

• Result copied into activation frame of lcm, to replace call to gcd

• Activation frame of gcd destroyed

• lcm continues execution using result. m*n/gcd(m,n) = 50*75/25 = 150 computed

• 150 returned to main_program, to replace call to lcm

• Activation frame of gcd destroyed

• main_program resumes and prints 15

64

(65)

a function to draw dashes

(66)

Autumn 2019 CS101@CSE IIT Bombay

A Function to Draw Dashes

void dash(int d){

while(d>10){

forward(10); penUp(); d -= 10;

forward(10); penDown(); d -= 10;

}

return;

}

main_program{

turtleSim();

repeat(4){dash(100); right(90);}

}

• dash assumes multiples of 20

• Generalization: Homework

66

(67)

Remarks

• Dash does not return a value, so its return type is void

• The return statement used in the body does not have a value after

the key word return

(68)

Autumn 2019 CS101@CSE IIT Bombay

Contract View Of Functions

• Function : piece of code which takes the responsibility of getting something done

• Specification : what the function is supposed to do

Typical form: If the arguments satisfy certain properties, then a certain value will be returned, or a certain action will happen certain properties = preconditions

• Example: gcd : If positive integers are given as arguments, then their GCD will be returned

• If preconditions are not satisfied, nothing is promised

68

(69)

Contract View of Functions (contd.)

• Function = contract between the programmer who wrote the function, and other programmers who use it

• Programmer who uses the function trusts the function writer

• Programmer who wrote the function does not care which program uses it

• Analogous to taking a car of servicing.

Mechanic will service/fix the car as long car is fixable.

Mechanic does not worry about who drives/drove the car.

Owner does not know who/how fix done.

(70)

Autumn 2019 CS101@CSE IIT Bombay

Contract View of Functions (contd.)

• Postconditions: After the function finishes execution, does it modify the state of the program?

• Example: After dash finishes its execution it might always leave the pen up (not true for the code given earlier)

• Exercise: Modify the code of dash to ensure that the pen is up at the end

• Post conditions must also be mentioned in the specification

• Writing clear specifications is very important

70

(71)

Some shortcomings

Using what we saw, it is not possible to write functions to do the following:

• A function that exchanges the values of two variables

• A function that returns not just one value as the result, but several.

For example, we might want a function to return polar coordinates

given Cartesian coordinates

(72)

Autumn 2019 CS101@CSE IIT Bombay

Exchanging The Values of Two Variables (Attempt 1)

void exchange(int m, int m){

int temp = m;

m = n; n = temp;

return;

}

main_program{

int a=1, b=2;

exchange(a,b);

cout << a <<‘ ‘<< b << endl;

}

72

(73)

Exchanging The Values of Two Variables (Attempt 1)

• Does not work. 1, 2 will get printed

• When exchange is called, 1, 2 are placed into m, n

• Execution of exchange exchanges values of m,n

• But the change in m, n is not reflected in the values of a, b of main_program

void exchange(int m, int n) {

int temp = m;

m = n; n = temp;

return;

}

main_program {

int a=1, b=2;

exchange(a,b);

cout << a <<‘ ‘<< b <<

endl;

}

(74)

Autumn 2019 CS101@CSE IIT Bombay

Reference Parameters

void exchange(int &m, int &n) {

int temp = m;

m = n; n = temp;

return;

}

main_program{

int a=1, b=2;

exchange(a,b);

cout << a <<‘ ‘<< b << endl;

}

74

(75)

Reference Parameters

• "&" before the name of the parameter: Says, do not

allocate space for this

parameter, but instead just use the variable from the calling program

• With this, when function changes m,n it is really changing a,b

• Such parameters are called reference parameters

void exchange(int &m, int &n) {

int temp = m;

m = n; n = temp;

return;

}

main_program {

int a=1, b=2;

exchange(a,b);

cout << a <<‘ ‘<< b <<

endl;

}

(76)

Autumn 2019 CS101@CSE IIT Bombay

Remark

• If a certain parameter is a reference parameter, then the corresponding argument is said to be passed by reference

76

(77)

Cartesian to Polar

void CtoP(double x, double y, double &radius, double

&theta){

radius = sqrt(x*x + y*y);

theta = atan2(y, x); //arctan return;

}

main_program{

double x=1, y=1, r, theta;

CtoP(x,y,r,theta);

cout << r <<‘ ‘<< theta << endl;

}

// Because r, theta in CtoP are reference parameters, // changing them changes the value of r, theta in

// the main program.

// Hence will print sqrt(2) and pi/4 (45 degrees)

(78)

Autumn 2019 CS101@CSE IIT Bombay

Pointers

• A pointer is a variable that can store addresses

– The memory location assoicated with a byte (different from what is stored in the byte) is said to be its address.

– If a computer has B bytes of memory ---- address will range from 0 to B-1.

What we accomplished using reference variables can also be accomplished using pointers

• Pointers will also be useful elsewhere as well.

78

(79)

how to find the address of a variable

• The operator & can be used to get the address of a variable. (The same & is used to mark reference parameters; but the meaning is different)

int t;

cout << &t << endl;

• This prints the address of variable t .

• Addresses are in hexadecimal (16) radix,

i.e. they will consist of a sequence of hexadecimal digits prefixed by “0x”. Note: hexadecimal digits:

0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F.

(80)

Autumn 2019 CS101@CSE IIT Bombay

variables that can store addresses

• To create a variable v in which you can store addresses of variables of type int you write:

int *v; // read as “int star v”

• The * is not multiplication. Think of it as (int*) v; where int* means the type: “address of int”.

int p;

v = &p;

cout << v <<‘ ‘<< &p << endl;

// both print same

• In general, to create a variable w to store addresses of variables of type T, write:

T* w;

80

(81)

the dereferencing operator *

• If v contains the address of p, then we can get to p (value of p) by writing *v.

int *v;

int p;

v = &p;

*v = 10; // as good as p = 10.

• Think of * as the inverse of &.

• &p : the address of the variable p

• *v : value of the variable whose address is in v

(82)

Autumn 2019 CS101@CSE IIT Bombay

Pointers in functions

void CtoP(double x, double y, double *pr, double *ptheta){

*pr = sqrt(x*x + y*y);

*ptheta = atan2(x,y);

return;

}

main_program{

double r, theta;

CtoP(1,1,&r,&theta);

cout << r <<‘ ‘

<< theta << endl;

}

main_program calls CtoP, supplying

&r, &theta as third and fourth arguments.

This is acceptable because

corresponding parameters have type double*.

The addresses are copied into pr, ptheta of CtoP.

*pr means the variable whose

address is in pr, in other words, the variable r of main_program.

Thus CtoP changes the variables of main_program.

Thus √2 = 1.41 and π/4 = 0.79 are printed.

82

(83)

Pointers in functions (swap)

void exchange(int &m, int &n) {

int temp = m;

m = n; n = temp;

return;

}

main_program {

int a=1, b=2;

exchange(a,b);

cout << a <<‘ ‘<< b <<

endl;

}

(84)

Autumn 2019 CS101@CSE IIT Bombay

Remarks

• You cannot store an address of an int variable into an int variable, nor store an int into a variable of type int*.

int *v, p;

v = p; // not allowed p = v; // not allowed

• For now, assume that the only operations you can perform on a variable of type T* are

– dereference it,

– store into it a value &v where v is of type T , – store it into another variable of type T*

– pass it to a function as an argument, provided corresponding parameter is of type T*

84

(85)

Concluding Remarks

• Functions allow us to divide the program into smaller parts such that each part deals with a particular functionality

• Apart from separation of computations, functions also allow separation of data spaces for computations

• This separation of concerns is a major help in understanding programs

• Functions can be seen as another control flow mechanism (apart from sequence, selection, and iteration)

• Function calls follow the LIFO (Last-In-First-Out) policy of execution

of nested calls

References

Related documents

• A pointer to a variable can be created in the main program and dereferenced during a function call. • This way a function can be allowed to modify variables in the main program,

Memory locations accessed: local variables/arrays of functions Statically allocated in stack segment when function is called.. Quick Recap of

• All local variables of a function allocated space in the activation record of the function..

I Proof sketch should be precise: refer to values of variables at specific points in the program?. I You should be able to extend the proof sketch

• For each macro-block (typically 16 x 16 or 8 x 8 in size) in the frame to be encoded, find the most similar macro- block in a reference frame (which could be the previous frame,

Minimizing Registers for Accessing Activation Records Reduce four pointer registers (stack, frame, args, and hard frame) to fewer registers. #define

– Keywords: Logic expression defining output, logic function, and input variable.. – Let’s use two switches to control the lightbulb by connecting them in series

This Java program is supplying to JPCT (Java program code transformer) which gives the output program called transformed program J 0 which is feed as input to JCUTE (Java