Upload
himanshuchawla654
View
217
Download
0
Embed Size (px)
Citation preview
8/10/2019 1.2Array String Recursion
1/36
Array
Array
Group of consecutive memory locations
Same name and type
To refer to an element, specify Array name
Position number
Format:
arrayname[position number]
First element at position 0
nelement array named c:
c[ 0 ], c[ 1 ]...c[ n 1 ]
8/10/2019 1.2Array String Recursion
2/36
Array
Arrays is a list of a finite number of homogeneous
data element.
The element of array are referenced by index set.
The element of the array are stored in successive
memory location.
Length of the array obtained by formula
Length=UB-LB+1
8/10/2019 1.2Array String Recursion
3/36
Representation of Array in memory
A be the Linear array then
LOC(A[I])=address of the element A[I] of the array A.
Base(A)=base address of A or the address of first
element of array.
For the address of any element of A-
A[K]=B+W*K
B= Base address of the array.W=no of words per memory cell for the array A.
K= Index of element.
8/10/2019 1.2Array String Recursion
4/36
Declaring Array
When declaring arrays, specify Name
Type of array
Number of elements
arrayType arrayName[ numberOfElements ];
Examples:
int c[ 10 ];
float myArray[ 3284 ];
Char name[20]; /String
Declaring multiple arrays of same type
Format similar to regular variables
Example: int b[ 100 ], x[ 27 ];
8/10/2019 1.2Array String Recursion
5/36
Examples Using Array
Initializersint n[ 5 ] = { 1, 2, 3, 4, 5 };
If not enough initializers, rightmost elements
become 0int n[ 5 ] = { 0 }
All elements 0
If too many a syntax error is produced syntax error
C arrays have no bounds checking
If size omitted, initializers determine itint n[ ] = { 1, 2, 3, 4, 5 };
5 initializers, therefore 5 element array
8/10/2019 1.2Array String Recursion
6/36
Types of Array
Single Dimensional array
syntax:- [size];
Exaple:- intiarr[3] = {2, 3, 4};
charcarr[20] = "c4learn" ;floatfarr[3] = {12.5,13.5,14.5} ;
Multi Dimensional array
syntax:- [r_sub][c_sub];
Example : - inta[3][3] = { 1,2,3 5,6,7 8,9,0 };
8/10/2019 1.2Array String Recursion
7/36
Passing Array to Function
Passing arrays
To pass an array argument to a function, specify the name of the array
without any brackets
int myArray[24];
myFunction(myArray,24); Array size usually passed to function
Arrays passed call-by-reference
Name of array is address of first element
Function knows where the array is stored
Modifies original memory locations
Passing array elements
Passed by call-by-value
Pass subscripted name (i.e.,myArray[3]) to function
8/10/2019 1.2Array String Recursion
8/36
Passing Array to Function
Function prototypevoid modifyArray( int b[], int
arraySize );
Parameter names optional in prototype int b[]could be written int []
int arraySizecould be simply int
8/10/2019 1.2Array String Recursion
9/36
Operations on Array
Traversal-Processing each element in the list.
Search-finding the location of element with a
given value or key.
Insertion-Adding a new element to the list.
Deletion-Removing an element from list
Sorting-Arranging the element in some order.
Merging-Combining two list to create new list.
8/10/2019 1.2Array String Recursion
10/36
Traversing the Array
TRAVERSE (A, UB,LB)
Ais a linear array,UB is upper bound and LB is lower bound.
1. set i:= LB [Initialize counter]
2. Repeat for i= LB to UB [visit element Display A[i]
[End of loop]
3. EXIT.
8/10/2019 1.2Array String Recursion
11/36
Insertion into Array
INSERT (A, len, pos, num)Ais a linear array,len is total no. of elements within array, posis the position at
which numwill be inserted.
1.check if (pos > len), if it is greater, then display message
Position is greater than array length.
Else:[Initialize counter] Set i: = len.
2. Repeat Steps 3 for i=len down to pos (Decrement loop from len to pos)
3. [Move jth element downward.] Set A [i + 1]: =A [i].
[End of step 2 loop]
4. [Insert element at required position]
Set A [pos]:=num.
6. [Reset LEN] Set LEN:=LEN+1
7. Display the new list of array.
8. EXIT.
8/10/2019 1.2Array String Recursion
12/36
Deletion from Array
DELETE (A ,len, pos)
Ais a linear array,len is total no. of elements within array, posis the position
from where the element should be deleted.
1.check if (pos > len), if it is greater, then display message
Position is greater than array length.
Else:
Set ITEM: = A [pos].
2. Repeat for J = pos to LEN1. (shift element one position upward)
Set A [J]: = A [J +1]. [End of loop]
3. [Reset the number N of elements in LA] Set LEN: = LEN - 1
4. EXIT
8/10/2019 1.2Array String Recursion
13/36
Matrix Addition
IfAand Bare matrices of the same size, then they can be
added. (This is similar to the restriction on adding vectors,
namely, only vectors from the same space Rncan be added;
you cannot add a 2vector to a 3vector, for example.) IfA=[aij] and B= [bij] are both mx nmatrices, then their sum, C=
A+ B, is also an mx nmatrix, and its entries are given by the
formula
Cij= Aij+ Bij
8/10/2019 1.2Array String Recursion
14/36
Matrix Addition
int main()
{
int a[3][3],b[3][3],c[3][3],i,j;
printf("Enter the First matrix->");
for(i=0;i
8/10/2019 1.2Array String Recursion
15/36
Matrix Additionfor(i=0;i
8/10/2019 1.2Array String Recursion
16/36
Matrix Multiplication
In order to form the productAB, the number of columns of
A must match the number of rows of B; if this condition does
not hold, then the productABis not defined. This criterion
follows from the restriction stated above for multiplying a row
matrix rby a column matrix c, namely that the number of
entries in rmust match the number of entries in c. IfAis mx n
and Bis nxp, then the productABis defined, and the size of
the product matrixABwill be mxp.
8/10/2019 1.2Array String Recursion
17/36
Matrix Multiplication
for(i=0;i
8/10/2019 1.2Array String Recursion
18/36
Polynomial
Representation of a Polynomial: A polynomial is an
expression that contains more than two terms. A term is
made up of coefficient and exponent. An example of
polynomial is
P(x) = 4x3+6x2+7x+9
A polynomial thus may be represented using arrays or linked
lists. Array representation assumes that the exponents of
the given expression are arranged from 0 to the highest
value (degree), which is represented by the subscript of thearray beginning with 0. The coefficients of the respective
exponent are placed at an appropriate index in the array.
8/10/2019 1.2Array String Recursion
19/36
How to implement this?
There are different ways of
implementing the polynomial ADT:
Array (not recommended)
Double Array (inefficient)
Linked List (preferred and
recommended)
8/10/2019 1.2Array String Recursion
20/36
Array Implementation:
p1(x) = 8x3
+ 3x2
+ 2x + 6p2(x) = 23x4+ 18x - 3
6 2 3 8
0 2
Index
represents
exponents
-3 18 0 0 23
0 42
p1(x) p2(x)
8/10/2019 1.2Array String Recursion
21/36
This is why arrays arent good to
represent polynomials:
p3(x) = 16x21- 3x5+ 2x + 6
6 2 0 0 -3 0 0 16
WASTE OF SPACE!
8/10/2019 1.2Array String Recursion
22/36
8/10/2019 1.2Array String Recursion
23/36
Linked List
Linked list Implementation:
p1(x) = 23x9+ 18x7+ 41x6+ 163x4+ 3
p2(x) = 4x6+ 10x4+ 12x + 8
23 9 18 7 41 6 18 7 3 0
4 6 10 4 12 1 8 0
P1
P2
NODE (contains coefficient & exponent)
TAIL (contains pointer)
8/10/2019 1.2Array String Recursion
24/36
Addition of two Polynomials:
For adding two polynomials using arrays is straightforward
method, since both the arrays may be added up element
wise beginning from 0 to n-1, resulting in addition of two
polynomials. Addition of two polynomials using linked list
requires comparing the exponents, and wherever the
exponents are found to be same, the coefficients are added
up. For terms with different exponents, the complete term
is simply added to the result thereby making it a part of
addition result. The complete program to add twopolynomials is given in subsequent section.
8/10/2019 1.2Array String Recursion
25/36
ALGORITHM:
Step 1: Start
Step 2: Declare structure polynomial
struct polynomial
{
int expo
int coef
}
Step 3: Read number of terms of the first polynomial, no of terms
Step 4: i=0, avail=0
Step 5: if i
8/10/2019 1.2Array String Recursion
26/36
Step 13: startD=avail
Step 14: while(startA
8/10/2019 1.2Array String Recursion
27/36
for(;startB=MAXTERMS) go to step2.else go tostep3
Step 2: Print Too many terms
Step 3: Assign coefficient to terms[avail].coef and exponent to
terms[avail].expo
8/10/2019 1.2Array String Recursion
28/36
Multiplication of two Polynomials:
Multiplication of two polynomials however requires
manipulation of each node such that the exponents are
added up and the coefficients are multiplied. After each
term of first polynomial is operated upon with each term of
the second polynomial, then the result has to be added up
by comparing the exponents and adding the coefficients for
similar exponents and including terms as such with dissimilar
exponents in the result.
8/10/2019 1.2Array String Recursion
29/36
Matrices
Vector and Matrices refer to the collection ofnumbers
Vector list of n number can be given in this form-
V=(V1,V2,V3..VN)
Matrix is the Array of m.n numbers arranged inrows and columns.
Scalar
Diagonal
SquareSparseUpper triangular
Lower triangular
Tridiagonal
8/10/2019 1.2Array String Recursion
30/36
Sparse Matrices
Matrices with high no of zero valuescalled Sparse Matrices.
Nonzero entries above the main diagonalis called upper triangular matrices
Nonzero entries below the main diagonal
is called lower triangular matrices
8/10/2019 1.2Array String Recursion
31/36
Recursion
When a function call itself, it is calledrecursion. Any recursive procedure must
have two properties:
1) There must be certain criteria, called
base criteria, for which the procedure
does not call itself.
2) Each time the procedure call itself, itmust be closer to the base criteria.
8/10/2019 1.2Array String Recursion
32/36
Types of recursion
Recursion is of two types:1) Direct recursion :- In this there is only
one function and it call itself.
2) Indirect recursion :- In this there
involved more than one function. Eg.
A() B()
{ {
B(); A();} }
8/10/2019 1.2Array String Recursion
33/36
Tail recursionTail recursion is important because it can be implemented more
efficiently than general recursion. When we make a normal
recursive call, we have to push the return address onto the call
stack then jump to the called function. It means that we need a
call stack whose size is linear in the depth of the recursive calls.When we have tail recursion we know that as soon as we return
from the recursive call we're going to immediately return as well,
so we can skip the entire chain of recursive functions returning
and return straight to the original caller. That means we don't
need a call stack at all for all of the recursive calls, and can
implement the final call as a simple jump, which saves us
space.
8/10/2019 1.2Array String Recursion
34/36
recursion
int fact(int x)
{
if (x == 0)
Return 1;
else
return (fact* fact(x-1));
}
8/10/2019 1.2Array String Recursion
35/36
Tail recursionfactorial(n)
{
return factorial1(n, 1);
}
factorial1(n, accumulator)
{
if (n == 0)
return accumulator;
elsereturn factorial1(n - 1, n * accumulator);
}
8/10/2019 1.2Array String Recursion
36/36
Efficiency of recursion
The fact is that recursion is rarely the most efficient approach to solvinga problem, and iteration is almost always more efficient. This is because
there is usually more overhead associated with making recursive calls
due to the fact that the call stack is so heavily used during recursion.
This means that many computer programming languages will spend
more time maintaining the call stack then they will actually performingthe necessary calculations. Recursion is generally used because of the
fact that it is simpler to implement, and it is usually more elegantthan
iterative solutions. Remember that anything thats done in recursion
can also be done iteratively, but with recursion there is generally a
performance drawback. But, depending on the problem that you are
trying to solve, that performance drawback can be very insignificantin
which case it makes sense to use recursion. With recursion, you also get
the added benefit that other programmers can more easily understand
d hi h i l d thi t h