CS 101:
Computer Programming and Utilization
Puru
withCS101 TAs and Staff
Course webpage: https://www.cse.iitb.ac.in/~cs101/
Lecture 11: How computers work? + Common
mathematical functions + Functions
Autumn 2019 CS101@CSE IIT Bombay
outline
• how computers work? (recap)
• examples of mathematical functions (howework)
• functions (slide 43)
2
recap
• Numbering systems
– decimal, binary, hexadecimal
• Number representation
– two’s complement (for integers)
– mantissa/significand + exponent form (for float/double)
• How computers work?
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
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
Autumn 2019 CS101@CSE IIT Bombay
organization of a computer
6
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
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
write operation
0 1
10010
11101000
"Write the number 11101000 (232) into the location number
Autumn 2019 CS101@CSE IIT Bombay
read operation
1
10010
11101000
"Read from the location number 10010 (18)
0
10
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
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
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.
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
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.
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
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
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
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
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
9970599705
20
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
Autumn 2019 CS101@CSE IIT Bombay
Common Mathematical
Functions
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
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
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
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
Error for the sine function after 7 terms
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
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
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+1x
2k-1/(2k-1)!
t
k-1= (-1)
kx
2k-3/(2k-3)!
t
k= (-1)
kx
2k-3/(2k-3)! * (-1)(x
2)/((2k-2)(2k-1))
= - t
k-1(x)
2/((2k-2)(2k-1)
30
Program Plan
• Loop control variable will be k
• In each iteration we calculate t
kfrom t
k-1• The term t
kis added to sum
• A variable term will keep track of t
k– At the beginning of k
thiteration, term will have the value t
k-1, and at the end of k
thiteration it will have the value t
k• After k
thiteration, 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
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
2. Numerical Integration (General)
• Integral from p to q = area under curve
• Approximate area by rectangles
p q
f
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
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
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
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
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
Land x
Rsuch that f(x
L) and f(x
R) are not both positive or both negative
38
Bisection Method For Finding Roots
xL
xR xM
• Because of continuity, there must be a root between
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
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
Autumn 2019 CS101@CSE IIT Bombay
other examples/techniques
• generalized square root f(x)=x
2-y
• Newton Raphson method for root finding
42
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;
Autumn 2019 CS101@CSE IIT Bombay
Functions
Functions
• Based on Chapter 9 of the book
An Introduction to Programming Through C++
by Abhiram Ranade (Tata McGraw Hill, 2014)
Autumn 2019 CS101@CSE IIT Bombay
can we define new commands?
• have we seen commands other than C++ syntax/commands?
46
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
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
why functions?
• write a program that prints the GCD of 36, 24, and of 99, 47
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
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
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
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)
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
(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
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
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;
}
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
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
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
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.
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
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
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
a function to draw dashes
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
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
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
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.
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
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
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
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;
}
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
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;
}
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
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)
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
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.
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
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
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
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;
}
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