Date post: | 04-Jun-2018 |
Category: |
Documents |
Upload: | dilip-matolkar |
View: | 225 times |
Download: | 0 times |
of 21
8/13/2019 Array and Structures
1/21
1
Unit 2: Array and Structures
Arrays Dynamically Allocated arrays
Structures and Unions
Polynomials Sparse Matrix
Representation of Multidimensional ArraysArray
It is a sequenced collection of related data items that share a common name It can be of any data type Lets you associate one name with a lot of variables of same type An array in C Programming Language can be defined as number of memory
locations, each of which can store the same data type and which can bereferences through the same variable name.
An array is a collective name given to a group of similar quantities.What is a subscript in array?
The individual elements of an array are referenced by appending a subscript, insquare brackets, behind the name.
The subscript itself can be any legitimate C expression that yields an integer orany other value
Array Declarations
Syntax for creating an arraydata_type Arrayname [int size];
If the size is not defined a default size of the array is taken by the compilerwhich is sufficient for most purposes.
Example:
float avg[5];It can be classified in terms of dimensions as 1-dimensional, 2-dimensional andmulti dimensional arrays.
The declaration int mark[3];declares array of size 3 and mark[0], mark[1] and mark[2] are the elements.
Initialization can be Compile time or Run time
Compile timeint a[3]={3,5,7};char b[3]={a,d,g};
8/13/2019 Array and Structures
2/21
2
Run timefor(i=0;i
8/13/2019 Array and Structures
3/21
3
Array Internals
Implementations of One Dimensional arrays In the above example lalu[5] creates storage for 5 integers. Each memory location is large enough to hold the single integer The address of the first location is called base address We calculate the address of the location like this.. +i*sizeof(int) where is the base address
How array treated in C ?
In C, array parameters are treated as pointers.
Array parameters treated as pointers because of efficiency. It is inefficient to copy
the array data in terms of both memory and time; and most of the times, when we
pass an array our intention is to just tell the array we interested in, not to create a
copy of the array.
/* Program to illustrate Array and its addresses */
#include#includevoid main(){int chintu [5]={4,5,6,7,8};int i;clrscr();for(i=0;i
8/13/2019 Array and Structures
4/21
4
Functions:
for all A Array,i index, x item, j, sizeinteger
Array Create(j, list) ::= return an array of jdimensions where list is a
j-tuple whose ith element is the size of the
ith dimension.Items are undefined.
ItemRetrieve(A, i) ::= if (i index) return the item associated withindex value i in array A
else return error
Array Store(A, i, x) ::= if (i in index)
return an array that is identical to array
A except the new pair has been
inserted else return error
end array
8/13/2019 Array and Structures
5/21
5
Dynamically Allocated Arrays
Allocation of memory during runtime for a given arrayOne Dimensional Array
The dynamicarrayis an array data structure which can be resized during runtime which means elements can be added and removed
The expression(int*)malloc(n*sizeof (int)) stores the number of elements in thememory. The malloc is basically used for memory allocation.
Declaring one dimensional array for dynamic allocation
int *ar;
Two Dimensional Arrays Dynamically allocation
C uses so-called array of arrays representation to represent a multidimensionalarray.
In this representation, a two dimensional array is represented as one Declaration: int **a;
Reallocation Of Memory Dynamically
realloc ; function is used to reallocate the memory dynamically
void main(){int *a;int i,n;int *b,n2;clrscr();printf("Enter the size..\n");scanf("%d",&n);a=(int *)malloc(n*sizeof(int));printf(" Enter the new size...\n");scanf("%d",&n2);a = (int *) realloc(a,n2*sizeof(int));printf("Enter the numbers...\n");for(i=0;i
8/13/2019 Array and Structures
6/21
6
Structures and Unions
Structures in C
Structures in C defines the group of contiguous (adjacent) fields, such asrecords or control blocks.
A structure is a collection of variables grouped together under a single name. Itprovides an elegant and powerful way for keeping related data together.
A structure contains an ordered group of data objects. Unlike the elements ofan array, the data objects within a structure can have varied data types. Eachdata object in a structure is a member or field. [IBM]
General Format of a Structure
struct tag_name{
datatype1 member1;datatype1 member2;datatype1 member3;
};
Example
Struct student{
char name[20];int rno;char college[20];
};
What is Structure Variable?
A variable which is used to access the members of the structure Variable used to initialize the members of the structure
Declaring Structure Variable
struct student{
char name[20];int rno;char collegename[20];float score;
} s1,s2;Here s1 and s2 are called as structure variables
8/13/2019 Array and Structures
7/21
7
Method 2
struct student{
char name[20];int rno;
char collegename[20];float score;
} ;struct student s1,s2;here s1 and s2 are the two structure variables
Method 3
struct student{
char name[20];
int rno;char collegename[20];float score;
} ;main()
{struct student s1,s2;
}
Accessing Members of the Structure
dot (.) operator is used selection operator ->
Method 1
struct student{char name[20];int rno;
}s1={sachin,34};
Method 2
struct student{char name[20];int rno;
};struct student s1={sachin,34};
8/13/2019 Array and Structures
8/21
8
Method 3
struct student{char name[20];int rno;
}main(){struct student s1={sachin,34};
}
Rules to be followed while using intializing Structures
We cannot initialize individual members of the structure inside the structuretemplate
The order of values enclosed in braces must match the order of members inthe structure definition
It is permitted to have a partial initialization . The uninitialized members will be assigned default values.
What is typedef in C?
The C language provides a facility called typedeffor creating synonyms[aliasing] for previously defined data type names. For example, the declaration:
A typedef can be used to eliminate the need for the struct key word in C. typedef int mint; mint a,b; // a and b are declared as two integers Int data type is renamed as mind This kind of declaration of data type is user defined data type
Example to illustrate typedef
#includetypedef struct{int a;float b;
}st;st k={2,4.5};void main(){printf("%d%f",k.a,k.b);}
8/13/2019 Array and Structures
9/21
9
Example to Illustrate initialize the values for the members assigning one variableto other and we can comapre
#includestruct name{
char name[20];int rno;
}s1={"anil",12};void main(){
struct name s2;s2=s1;if(s2.rno==s1.rno)
{printf(" We are similar \n");printf("%s3%d",s1.name,s1.rno);printf("%s3%d",s2.name,s2.rno);
}}
Why Unions ?
This can save memory if you have a group of data where only one of the types is used
at a time.
Unions
Like a structure, a union is also a user defined data type. Concept borrowed from structures, hence syntax is similar to structures The members of a union share a single storage space. Only ONE member of each union can be referenced at a time. Amount of space allocated for storage is the amount needed for the largest
member of the union.
Some Points on Unions
Sizeof union is size of its biggest member Unions most often contain different types of structures Can only initialize first member of union Can assign (copy) one union variable to another Can pass union or pointer to union as function argument Function can return union type
8/13/2019 Array and Structures
10/21
10
Example
union student{char name[10];int rno;
float score;}
Arrays within the structures
We can have array as member of the structureExample:
struct student{
int rno;
char name[20];int sub[3];
}s1;
Arrays of structures
struct stud{int rno;char name[20];int sub[3];
}s[3];
Nesting of structures
struct s{
int a;struct{
float b;}f;
}r;A structure can have structure within it, we call this as nesting of structures
Structures and Functions
The first method is pass each member of the structure as an actual argument ofthe function call
Passing a copy of entire structure to the called function
8/13/2019 Array and Structures
11/21
11
Internal Representation of structures
Memory allocated in structures is contiguous Allocation is done based on the word size(machines bit size) For example some machines are 32 bit, some may be 64 bits To enhance the speed of execution data alignment is done it is done by the
help of padding mechanism. Padding is nothing but adding some extra bits in the memory of the member Control moves based on the word size, we call this as offset. For more details move to next slide
What is alignment and Padding in Structures?
Data structure alignmentis the way data is arranged and accessed incomputer memory. It consists of two separate but related issues: data
alignmentand data structure padding. When a modern computer reads from or
writes to a memory address, it will do this in word sized chunks (e.g. 4 bytechunks on a 32-bit system).
Data alignmentmeans putting the data at a memory offset equal to somemultiple of the word size, which increases the system's performance due to the
way the CPU handles memory.
To align the data, it may be necessary to insert some meaningless bytesbetween the end of the last data structure and the start of the next, which
is data structure padding.
Typical alignment for Borland C
A char(one byte) will be 1-byte aligned. A short(two bytes) will be 2-byte aligned. An int(four bytes) will be 4-byte aligned. A long(four bytes) will be 4-byte aligned. A float(four bytes) will be 4-byte aligned. A double (8 Bytes) will be 8 bytes aligned A long double(10 Bytes) will be 10 bytes aligned
How the structure Padding is done?
Padding will be done by compiler to structures members and to the structureas a whole also. Compiler pads structure as whole because this allows each
member of structure aligned in array of structures.
Inorder to avoid such misalignment, compiler will introduce alignmentrequirement to every structure. It will be as that of the largest member of the
structure
8/13/2019 Array and Structures
12/21
12
Example
Struct EX{Char a;Short int b;
Char c;Long d;
}; Due to structure paddingthis structure size is
Few Points.on Padding
Padding does NOT occur at the beginning of a structure. The value of padding bytes or bits are implementation defined.
Self referential Structures
A structure calling a same type of structure is referred to as self referentialRepresentation of Singly Linked list
struct node{
int info;struct node *link
};
typedef struct node *NODE; Meaning of this: A node is of the type struct and contains info field and link
filed
8/13/2019 Array and Structures
13/21
13
Polynomials
In mathematics, a polynomial(from Greekpoly, means "many "binomial[is
an expression of finite length constructed from variables and constants, using only
the operations of addition, subtraction, multiplication, and non-
negative integer exponents.
Few Things about polynomial
3x20+ 2x5+4 X is the variables name Exponent: 20,5 are the exponent Coefficient: 3,4 2 are the coefficients Degree: The largest exponent of a polynomial is called degree. Here it is 20 The term with exponent equal to zero doesnt show the variable 6x2This is NOT a polynomial term......because the variable has a negative
exponent. 1/x2 This is NOTa polynomial term......because the variable is in the
denominator. 4x2This IS a polynomial term......because it obeys all the rules.
Adding Polynomial ; Horizonatlly
(3x3+ 3x24x+ 5) + (x32x2+ x4)
= 3x3+ 3x24x+ 5 + x32x2+ x4
= 3x3+ x3+ 3x22x24x+ x+ 54
= 4x3+ 1x23x+ 1
Adding Polynomial ; Vertically
http://localhost/var/www/apps/conversion/tmp/scratch_10/Head%20in%20the%20toilet%20prank%20-%20Just%20For%20Laughs.flvhttp://localhost/var/www/apps/conversion/tmp/scratch_10/Head%20in%20the%20toilet%20prank%20-%20Just%20For%20Laughs.flvhttp://localhost/var/www/apps/conversion/tmp/scratch_10/Head%20in%20the%20toilet%20prank%20-%20Just%20For%20Laughs.flvhttp://localhost/var/www/apps/conversion/tmp/scratch_10/Head%20in%20the%20toilet%20prank%20-%20Just%20For%20Laughs.flv8/13/2019 Array and Structures
14/21
14
Abstract Data type
The list contain items that are written in the form(item0,item1, item n-1 Finding the length, n of the list. Retrieving the items from the list 0i
8/13/2019 Array and Structures
15/21
15
Polynomial ADT (continued)A single variable polynomial can be generalized as:
What kinds of operations?
Here are the most common operations on a polynomial: Add & Subtract Multiply Differentiate Integrate etc
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:[ two separate arrays] p1(x) = 8x3+ 3x2+ 2x + 6 p2(x) = 23x4+ 18x - 3 Double Array Implementation: Say you want to represent the following two polynomials: p1(x) = 23x9+ 18x7- 41x6+ 163x4- 5x + 3 p2(x) = 4x6+ 10x4+ 12x + 8
Representation of Polynomial using arrays of structures
Max 100typedef struct{
float coeff;int expon;
} polynomial;
Polynomial terms[Max]// Single array
This is why arrays arent good to represent polynomials:p3(x) = 16x21- 3x5+ 2x + 6
8/13/2019 Array and Structures
16/21
16
Here We are using the concept Global array [Single array]
Both polynomials can be represented by only one array.[Single array] We use few things like start A, finish A, start B, finish B, and avail. In the beginning avail=0 Finish A=startA + n-1
Polynomial Addition
/* d =a + b, where a, b, and d are polynomials */d = Zero( )while (! IsZero(a) && ! IsZero(b))Do{switch COMPARE (Lead_Exp(a), Lead_Exp(b)){case -1: d =Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b));
b = Remove(b, Lead_Exp(b));break;
case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b));if (sum)
{Attach (d, sum, Lead_Exp(a));a = Remove(a , Lead_Exp(a));b = Remove(b , Lead_Exp(b));
}break;
case 1: d =Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a));a = Remove(a, Lead_Exp(a));
}}
insert any remaining terms of a or b into d
Advantages of using an Array:
only good for non-sparse polynomials. ease of storage and retrieval. easy implementation
Disadvantages of using an Array:
have to allocate array size ahead of time.
huge array size required for sparse polynomials. Waste of space and runtime. waste space when sparse.
8/13/2019 Array and Structures
17/21
17
Sparse Matrix
Example of Sparse Matrix
In this example of the 100 elements, only 17 are nonzero. The rest of theelements are zero. We call this a sparse matrix.
While it is not costly to store all 100 numbers of the above matrix on acomputer, consider what happens as the matrix gets bigger.
If the number of rows grows to thousands or millions, the number of elementsbecomes too large to store.
If, however, the number of the elements that are nonzero is small, we can stillstore the matrix if we only store those numbers and assume the rest arezero!This is a sparse storage scheme.
Sparse Matrix ADTObjects: a set of triples, , where rowand column are integers and form a unique combination, and
value comes from the set item.
Methods: for all a, b Sparse_Matrix, x item, i, j, max_col, max_row index
Sparse_Marix Create(max_row, max_col) ::= return a Sparse_matrix that can hold upto max_items = max _row max_col and whose maximum row size is max_row andwhose maximum column size is max_col.
Sparse_Matrix Transpose(a) ::= return the matrix produced by interchanging the rowand column value of every triple.
Sparse_Matrix Add(a, b) ::=if the dimensions of a and b are the same return error
Sparse_Matrix Multiply(a,b)::= if number of columns in a equals number of rows in breturn the matrix d produced by multiply a by b according to the formula: d [i] [j] =S(a[i][k]b[k][j]) where d (i, j) is the (i,j)th element else return error.
8/13/2019 Array and Structures
18/21
18
Sparse Matrix Representation
(1) Represented by a two-dimensional array.
Sparse matrix wastes space.(2) Each element is characterized by TRIPLET .Sparse_matrix Create(max_row, max_col) ::= #define MAX_TERMS 101 /* maximum
number of terms +1*/typedef struct
{int col;int row;int value;
} term;term A[MAX_TERMS]
Given Matrix
Sparse Matrix Operations
Transpose of a sparse matrix.Sparse Matrix Transpose of Sparse Matrix
row col value row col value
a[0] 6 6 8 b[0] 6 6 8
[1] 0 0 15 [1] 0 0 15
[2] 0 3 22 [2] 0 4 91
[3] 0 5 -15 [3] 1 1 11
[4] 1 1 11 [4] 2 1 3
[5] 1 2 3 [5] 2 5 28
[6] 2 3 -6 [6] 3 0 22
[7] 4 0 91 [7] 3 2 -6
[8] 5 2 28 [8] 5 0 -15
Row/COLCOL0
COL1
COL2
COL3
COL4
COL5
Row0
15 0 0 22 0 -15
Row 1
0 11 3 0 0 0
Row2
0 0 0 -6 0 0
Row3
0 0 0 0 0 0
Row4
91 0 0 0 0 0
Row5
0 O 28 0 0 0
http://localhost/var/www/apps/conversion/tmp/scratch_10/SPARSENEW2.C8/13/2019 Array and Structures
19/21
19
Transpose of a Sparse Matrix ;
void transpose (term a[], term b[])/* b is set to the transpose of a */{
int n, i, j, currentb;
n = a[0].value; /* total number of elements */b[0].row = a[0].col; /* rows in b = columns in a */b[0].col = a[0].row; /*columns in b = rows in a */b[0].value = n;if (n > 0) { /*non zero matrix */currentb = 1;for (i = 0; i < a[0].col; i++) /* transpose by columns in a */for( j = 1; j
8/13/2019 Array and Structures
20/21
20
Let the two arrays row_terms and starting_pos be shared. The fast-transpose algorithm only uses a little memory to record the matrix and
takes only O(cols+elements) amount of time, which is efficient considering the
number of elements equals cols*rows.
void fast_transpose(term a[ ], term b[ ]){ /* the transpose of a is placed in b */int row_terms[MAX_COL], starting_pos[MAX_COL];int i, j, num_cols = a[0].col, num_terms = a[0].value;b[0].row = num_cols;b[0].col = a[0].row;b[0].value = num_terms;if (num_terms > 0){ /*nonzero matrix*/for (i = 0; i < num_cols; i++)row_terms[i] = 0;for (i = 1; i
8/13/2019 Array and Structures
21/21
21
Representation of Multidimensional Arrays
.