You are on page 1of 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
n element array named c:
c[ 0 ], c[ 1 ]...c[ n 1 ]

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

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 AA[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.

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 ];

Examples Using Array


Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };

If not enough initializers, rightmost elements


become 0
int 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 it


int n[ ] = { 1, 2, 3, 4, 5 };

5 initializers, therefore 5 element array

Types of Array
Single Dimensional array
syntax:- <data-type> <array_name> [size];
Exaple:int iarr[3] = {2, 3, 4};
char carr[20] = "c4learn" ;
float farr[3] = {12.5,13.5,14.5} ;
Multi Dimensional array
syntax:- <data-type> <array_name> [r_sub][c_sub];
Example : int a[3][3] = { 1,2,3 5,6,7 8,9,0 };

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

Passing Array to Function


Function prototype
void modifyArray( int b[], int
arraySize );

Parameter names optional in prototype


int b[] could be written int []
int arraySize could be simply int

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.

Traversing the Array


TRAVERSE (A, UB,LB)
A is 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.

Insertion into Array

INSERT (A, len, pos, num)


A is a linear array, len is total no. of elements within array, pos is the position at
which num will 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.

Deletion from Array

DELETE (A ,len, pos)


A is a linear array, len is total no. of elements within array, pos is 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 LEN 1. (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

Matrix Addition
If A and B are 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 R n can be added;
you cannot add a 2vector to a 3vector, for example.) If A =
[aij] and B = [bij] are both m x n matrices, then their sum, C =
A + B, is also an m x n matrix, and its entries are given by the
formula
Cij= Aij+ Bij

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<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);

Matrix Addition
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n");
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return 0;
}

Matrix Multiplication
In order to form the product AB, the number of columns of
A must match the number of rows of B; if this condition does
not hold, then the product AB is not defined. This criterion
follows from the restriction stated above for multiplying a row
matrix r by a column matrix c, namely that the number of
entries in r must match the number of entries in c. If A is m x n
and B is n x p, then the product AB is defined, and the size of
the product matrix AB will be m x p.

Matrix Multiplication
for(i=0;i<m;i++)
for(j=0;j<p;j++)
c[i][j]=0;
for(i=0;i<m;i++){ //row of first matrix
for(j=0;j<p;j++){ //column of second matrix
sum=0;
for(k=0;k<n;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
}}

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 the
array beginning with 0. The coefficients of the respective
exponent are placed at an appropriate index in the array.

How to implement this?

There are different ways of


implementing the polynomial ADT:
Array (not recommended)
Double Array (inefficient)
Linked List (preferred and
recommended)

Array Implementation:
p1(x) = 8x3 + 3x2 + 2x + 6
p2(x) = 23x4 + 18x - 3
p1(x)

6
0

p2(x)

-3
0

Index
represents
exponents

18

0
2

23
4

This is why arrays arent good to


represent polynomials:
p3(x) = 16x21 - 3x5 + 2x + 6

-3

WASTE OF SPACE!

16

Double Array
p1(x) = 23x9 + 18x7 - 41x6 + 163x4 - 5x
+3
p2(x) = 4x6 + 10x4 + 12x + 8
Start p1(x)

Start p2(x)

Coefficient

23

18

-41 163
6

-5

10

12

Exponent
End p1(x)

End p2(x)

Linked List
Linked list Implementation:
p1(x) = 23x9 + 18x7 + 41x6 + 163x4 + 3
p2(x) = 4x6 + 10x4 + 12x + 8
P1

23

18

41

18

TAIL (contains pointer)

P2

10

12

NODE (contains coefficient & exponent)

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 two
polynomials is given in subsequent section.

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<noofterms, repeat steps 6 and 7
Step 6: Read terms[avail].coef and terms[avail].expo
Step 7: i=i+1, avail++a
Step 8: Read number of terms of the second polynomial, noofterms
Step 9: i=0
Step 10: if i<noofterms, repeat steps 11 and 12
Step 11: Read terms[avail].coef and terms[avail].expo
Step 12: i=i+1, avail++

Step 13: startD=avail


Step 14: while(startA<=finishA)&&(startB<=finishB), repeat steps 14 to
17
Step 14: if terms[startA].expo>terms[startB].expo
Call attach(terms[startB].coeff,terms[startB].expo)
startB++
Step 15: if terms[startA].expo=terms[startB].expo
coefficient= terms[startA].coeff+terms[startB].coeff
if coefficient!=0
Call attach(coefficient,terms[startB].expo)
startA++;
startB++;
Step 16: if terms[startA].expo<terms[startB].expo
Call attach(terms[startA].coeff,terms[startA].expo)
startA++;
Step 17: for(;startA<=finishA;startA++)
Call attach(terms[startA].coeff,terms[startA].expo)

for(;startB<=finishB;startB++)
Call attach(terms[startB].coeff,terms[startB].expo)
Step 18: *finishD=avail-1
Step 19: Stop
Algorithm for function Attach
Step 1: if(avail>=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

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.

Matrices
Vector and Matrices refer to the collection of
numbers
Vector list of n number can be given in this formV=(V1,V2,V3..VN)
Matrix is the Array of m.n numbers arranged in
rows and columns.
Scalar
Diagonal
Square
Sparse
Upper triangular
Lower triangular
Tridiagonal

Sparse Matrices
Matrices with high no of zero values
called Sparse Matrices.
Nonzero entries above the main diagonal
is called upper triangular matrices
Nonzero entries below the main diagonal
is called lower triangular matrices

Recursion
When a function call itself, it is called
recursion. 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, it
must be closer to the base criteria.

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();
}
}

Tail recursion
Tail 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.

recursion
int fact(int x)
{
if (x == 0)
Return 1;
else
return (fact* fact(x-1));
}

Tail recursion

factorial(n)
{
return factorial1(n, 1);
}
factorial1(n, accumulator)
{
if (n == 0)
return accumulator;
else
return factorial1(n - 1, n * accumulator);
}

Efficiency of recursion
The fact is that recursion is rarely the most efficient approach to solving
a 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 performing
the necessary calculations. Recursion is generally used because of the
fact that it is simpler to implement, and it is usually more elegant than
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 insignificant in
which case it makes sense to use recursion. With recursion, you also get
the added benefit that other programmers can more easily understand
your code which is always a good thing to have.

You might also like