cs101 introduction to computing › asahu › cs101-2017 › lec13.pdf · cs101 introduction to...
Post on 30-May-2020
18 Views
Preview:
TRANSCRIPT
CS101 Introduction to computing
Problem Solving (Computing)
&& Array and Pointer
A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.
Indian Institute of Technology Guwahati
1
Outline• Loop invariant and loop termination• Man Problem Sol ing E amples• Many Problem Solving Examples
–7 Problems (Solution Method not given)
–3 problems (Solution Method given)p (So u o e od g e )
f G “ l iReference : R G Dromey, “How to solve it by Computer”, Pearson Education India, 2009
2
Problem Solving Example • Set A (Solution Method not given)
1 N h f X1. Nth Power of X 2. Square root of a number 3. Factorial of N 4 Reverse a number4. Reverse a number 5. Finding value of unknown by question
answersanswers 6. Value of Nth Fibonacci Number7. GCD to two numbers
3
Problem Solving Example
• Set B (Solution Method given)1. Finding values Sin(x) using series sum 2 Value of PI2. Value of PI 3. Finding root of a function Bisection
Methods
4
Greatest Common Divisor
• Given two numbers n and m find their di igreatest common divisor
• possible approachp pp– find the common primes in the prime factorizationsfactorizations
• Basic Approaches
C Code: GCD using substractionint n1, n2;;// Put code for Input n1 and n2// Put code for Input n1 and n2while (n1!=n2) {
while (n1 > n2) n1 = n1 - n2;
while (n1 > n2) n1 = n1 n2;while (n2 > n1) n2 = n2 - n1;
}}//Put code to Display GCD=n1
7
C Code: GCD using substractionint n1, n2;;// Put code for Input n1 and n2// Put code for Input n1 and n2while (n1!=n2) {
if (n1 > n2) n1 = n1- n2;if (n1 > n2) n1 = n1 n2;else n2 = n2 - n1;
}}//Put code to Display GCD=n1
S b h i li8
Same behavior as earlier code
Euclid’s AlgorithmEuclid s Algorithm• Euclid’s algorithm: one of the oldest algorithms
d l b ( )• Based on simple observation (assume n > m)gcd(n,m) = gcd(n‐m,m) (and hence)gcd(n,m) = gcd(m, modulo(n,m))
• uses this property to reduce the smalleruses this property to reduce the smaller number repeatedly
• until the smaller number is 0• until the smaller number is 0• larger number then is the gcd
C Code: GCD using reminder int n1, n2, GCD;// Put code for Input n1 and n2// Put code for Input n1 and n2while (!(n1==0 || n2==0)) {
//while (n1 > n2) n1 = n1 n2;//while (n1 > n2) n1 = n1 - n2;
if (n1>n2) n1=n1%n2;//while (n2 > n1) n2 = n2 - n1;
else n2=n2%n1; }if (n1==0) GCD=n2; else GCD=n1;//P t d t Di l GCD//Put code to Display GCD
10
Euclid’s Algorithm• A fixed number of operations performed in each iteration
• Time depends on number of iterations• after every 2 iterations value of m is reduced• after every 2 iterations, value of m is reduced by at least half
if d l ( ) > /2 th– if modulo(n,m) > m/2 thenmodulo(m,modulo(n,m)) < m/2
b f (l )• number of iterations is at most 2(log2m+1)
Problem Solving Example
• Set B (Solution Method given)1. Value of PI 2 Finding values sin(x) using series2. Finding values sin(x) using series3. Finding root of a function Bisection
Methods
12
Estimating π using Randomized h dMethod
• Area of Circle : π . r2
( )
Area of Circle : π . r• If r =1, A=π• Area of circle in (+ +)
M
(x,y)• Area of circle in (+,+) quadrant : π/4
• Area of unit squareN
M• Area of unit square [x=0 to 1][y=0 to 1] is 1G t N d i t• Generate N random points – Point have x, y valuesB t [ 0 t 1][ 0 t 1]– Between [x=0 to 1][y=0 to 1]
Estimating π using Randomized Method
• The probability of a random point lying inside the unit circle:
Method
point lying inside the unit circle:
(x,y)
• If pick a random point N times andM of those times the point N
M
and M of those times the point lies inside the unit circle:
N
• If N becomes very large P=P0If N becomes very large, P=P
Value of PI: Randomized Method#define N 10000
int M=0,i;double x,y,z; for ( i=0; i<N; i++) {
x = (double)rand()/RAND_MAX;y = (double)rand()/RAND MAX;_z = x*x+y*y;if (z<=1) M++;( )}
pi=4.0*(double)M/N;pi 4.0 (double)M/N;// Display value of PI
Finding values Sin(x) using iseries sum
• Problem: Design an efficient approach to l t th f ti i ( ) d fi d bevaluate the function sin(x) as defined by
infinite series of expansion i ( ) /1! 3/3! 5/5! 7/7!sin(x) = x/1! – x3/3! +x5/5! –x7/7!+ …
• Approach 1– For every term to be used : calculate the value of ith term : Suppose we want to calculate xi/i!Sum all the terms upto Ti 1; j 1;– Sum all the terms uptoterm > accuracy
Ti=1; j=1; while(j<=i) {
Ti=Ti * x/j;Ti Ti x/j;j = j+1;
}
Finding values Sin(x) using iseries sum
• sin(x) = x/1! – x3/3! +x5/5! –x7/7!+ … • Approach 2
– Current ith term = ‐x2/(i*(i‐1)) * Previous i‐1th Term /( ( ))– Sum all the terms upto term > accuracy
Finding values Sin(x) using iseries sum
• sin(x) = x/1! – x3/3! +x5/5! –x7/7!+ … • Approach 2
– Current ith term = ‐x2/(i*(i‐1)) * Previous i‐1th Term /( ( ))– Sum all the terms upto term > accuracy
• Each iterationi = i+2;i = i+2;term = - term * x*x/(i*(i-1));Si V l Si V l+ tSinxVal= SinxVal+ term;
C Code Sin(x) using series sumC Code Sin(x) using series sum int i=1; fl t Si XV l 0 tfloat SinXVal=0, term;float x, sqrOfx, accuracy;// Put code for Input x & accuracy// Put code for Input x & accuracywhile (term < accuracy) {
i = i+2;i i 2;term = - term * x*x/(i*(i-1));SinxVal= SinxVal+ term;SinxVal SinxVal+ term;
}//Put code to Display SinxValp y
Bisection Method • Bisection Method is a numerical method in Mathematics to find a root of a given functiong f
• Root of a function f(x) is value a such that:f(a) = 0f(a) 0
• Example:Function: f(x) = x2 4Function: f(x) = x ‐ 4 Roots: x = ‐2, x = 2
Because:Because: f(‐2) = (‐2)2 ‐ 4 = 4 ‐ 4 = 0 f(2) (2)2 4 4 4 0f(2) = (2)2 ‐ 4 = 4 ‐ 4 = 0
A Mathematical Property • If a function f(x) is continuous on the interval [a..b] and sign of f(a) ≠ sign of f(b), then
• There is a value c [a..b] such that: f(c) = 0I.e., there is a root c in the interval [a..b]
Bisection Method• Is a successive approximation methodthat narrows down an interval –that contains a root of the function f(x)Gi i iti l i t l [ b]• Given an initial interval [a..b]–Contains a root– sign of f(a) ≠ sign of f(b)
Bisection Method• Bisection Method will
–Cut the interval into 2 halves and check which half interval contains a root of the function
–will keep cut the interval in halves until the resulting interval is extremely smallresulting interval is extremely small
The root is then approximately equal to l i th fi l ( ll) i t lany value in the final (very small) interval.
Bisection Method ExampleBisection Method ExampleWe cut the interval [a..b] in the middle: m = (a+b)/2(a+b)/2
Bisection Method Example• Because sign of f(m) ≠ sign of f(a) , we proceedwith the search in the new interval [a b]:with the search in the new interval [a..b]:
C Code: Bisection MethodC Code: Bisection Method For Function : x^3+2x‐5, a=2, b =3float a, b, Fa, Fb, Fx;//Code for Input a, b and accuracyF * * 2* 5 Fb b*b*b 2*b 5Fa=a*a*a-2*a-5; Fb=b*b*b-2*b-5;x=a;x1=b;while( abs(x x1)>accuracy) {while( abs(x-x1)>accuracy) {
x1=x; x=(a+b)/2;Fx=x*x*x-2x-5;Fx x x x 2x 5;if(Fa*Fx<0) b=x; else a=x;
}}//Code print root X
30
CS101 Introduction to computingCS101 Introduction to computing
Array and PointerArray and Pointer
A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.
Indian Institute of Technology Guwahati
Outline• Array Definition, Declaration, Use• Array Examples• PointerPointer
–Memory access –Access using pointer
• Basic Pointer Arithmetic• Basic Pointer Arithmetic
ObjectivesObjectives• Be able to use
–arrays, pointers, and strings in C programsprograms
• Be able to explain the p–Representation of these data types at the machine level including theirthe machine level including their similarities and differences
Definition – ArrayDefinition Array
• A collection of objects of the same typej ypstored contiguously in memory under one namename–May be type of any kind of variable–May even be collection of arrays!
• For ease of access to any member of arrayy y• Can be think as a group
Examples• int A[10]
• An array of ten integers• An array of ten integers• A[0], A[1], …, A[9]
• double B[20]• An array of twenty long floating point y y g g pnumbers
• B[0] B[1] B[19]B[0], B[1], …, B[19]
• Array indexes always start at zero in C
ExamplesExamples• int D[10][20]
• An array of ten rows, each of which is an array of twenty integers
• D[0][0], D[0][1], …, D[1][0], D[1][1], …, D[9][19]
• Not used so often as arrays of pointers
Array ElementArray Element
• May be used wherever a variable of the• May be used wherever a variable of the same type may be used
I i (i l di )• In an expression (including arguments)• On left side of assignment
• Examples:–
A[3] = x + y;x = y – A[3];z = sin(A[i]) + cos(B[j]);z = sin(A[i]) + cos(B[j]);
Array ElementsArray Elements
• Generic form:––ArrayName[integer‐expression]ArrayName[integer expression] [integer–ArrayName[integer‐expression] [integer‐expression]
h d l i f h– Same type as the underlying type of the array
• Definition:– Array Index – the expression between the square bracketsq
Array Elements• Array elements are commonly used in loops• E.g., for(i=0; i < max; i++)
A[i] = i*i;A[i] i i;
sum = 0; for(j=0;j<max;j++) sum += B[j];
sum = 0;sum 0; for (count=0; count<30; count++){
scanf("%f", &A[count]);Sum += A[count];
}
Array: Initialization and AccessingArray: Initialization and Accessing
int A[5] i; //definingint A[5], i; //defining//initializingfor (i 0; i<5; i++)for (i=0; i<5; i++)
A[i]=i; ////accessing the array for (i=0; i<5; i++)
printf("%d, ", A[i]);
Memory Organization···
2n‐10 1 2 3 4 5 6 7 8 9 10 11
• All modern processors have memories organized as sequence of numbered bytesorganized as sequence of numbered bytes–Many (but not all) are linear sequences
• Definitions:––Byte: an 8‐bit memory cell capable ofByte: an 8 bit memory cell capable of storing a value in range 0 … 255
b b h h ll–Address: number by which a memory cell is identified
Memory Organization (continued)···
2n‐10 1 2 3 4 5 6 7 8 9 10 11
• Larger data types are sequences of bytes–short int – 2 B, int – 4 B, long –8 B , , g–float – 4 B, double – 8 B
• (Almost) al a s aligned to m ltiple of si e in• (Almost) always aligned to multiple of size in bytes
• Address is “first” byte of sequence–May be low‐order or high‐order byteMay be low order or high order byte–Big endian or Little endian
top related