DS Module I GangaHoli
DS Module I GangaHoli
DS Module I GangaHoli
Based on the structures and arrangement of data, non-primitive data structures are further
classified into linear and non-linear.
A data structure is said to be linear if its elements form a sequence or a linear list. In linear data
structures, the data is arranged in a linear fashion although the way they are stored in memory need not be
sequential. Arrays, linked list, stacks and queues are the examples of linear data structures.
Conversely, a data structure is said to be a non-linear if the data is not arranged in sequence. The
insertion and deletion of data is therefore not possible in a linear fashion. Trees and graphs are examples
of non-linear data structures.
3. What are the data structures operations?
The data appearing in our data structures are processed by means of certain operations. In fact,
the particular data structure that one chooses for a given situation depends largely on the frequency with
which specific operations are performed.
1. Traversing: Accessing each record exactly once so that certain items in the record maybe processed.
(This accessing and processing is sometimes called "visiting" the record).
2. Searching: Finding the location of the record with a given key value, or finding the locations of all
records which satisfy one or more conditions.
3. Inserting: Adding a new record to the structure.
4. Deleting: Removing a record from the structure.
The following two operations are used in special situations,
5. Sorting: Arranging the records in some logical order.
6. Merging: Combining the records of two different sorted files into a single sorted file.
Set J := N
2. Repeat Steps 3 and 4 while J >= K
3. Move Jth element downward
Set[J+1] := A[J]
4. Decrease counter
Set J := J-1
End of step 2 loop
5. Insert element
Set A[K] := ITEM
6. Reset N
Set N := N+1
7. Exit
(iii) Deletion
Deletion refers to the operation of removing an element from the array.
Deleting the element from the end of an array is not a problem, but deleting from middle requires
movement of each element upwards in order to fill up the void in the array.
Algorithm for Deletion
Let A be a linear array. The function used to delete from the array is DELETE(a, N, K, ITEM)
where, N is the number of elements, K is the positive integer such that K<=N. The algorithm delets Kth
element from the array.
1. Set ITEM := A[k]
2. Repeat for J - K to N-1
[Move J+1 element upward]
Set A[J] := A[J+1]
End of loop
3. Reset the number N of elements in A
Set N := N-1
4. Exit
6. Describe the method to calculate the actual memory address of the array
location.
Address Calculation in One Dimension Array:
Array of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Example: Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2
bytes in the memory. Find the address of B[1700].
Solution: The given values are: B = 1020, LB = 1300, W = 2, I = 1700
Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
Dr. Ganga Holi, ISE Dept., Global academy of Technology
3
Module I-Arrays, Strings,
Then the address LOC(K1, K2, K3…...Kn) of an ordinary element of C array can be obtained from the
formula
Base(C )+w[(((…(EnLn-1 +En-1 )Ln-2 + En-2 )Ln-3 + +E3)L2 + E2)L1 +E1)
or
from the formula Base( C )+ w[(…((E1L2 +E2 )L3 + E3 )L4 + ….+En-1)Ln+ En)
While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations.
Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to
achieve linearization: Row-Major and Column-Major.
Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System
Row Major System: The address of a location in Row Major System is calculated using the following
formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System: The address of a location in Column Major System is calculated using the
following formula:
Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
Where, B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
7. What are Polynomials and Sparse matrices? Explain with example.
Polynomial is an expression consisting of variables and co-efficients which only employs
operations of addition, subtraction and multiplication.
Ex: x^2-4x+7 is a single variable equation.
x^3+xyz^2+x^2y+z+10 is a 3 variable polynomial equation.
The largest exponent (power) of a polynomial is called its degree. Co-efficients that are zero are not
displayed.
term a[100];
int main()
{ int i, x, n,m, sum=0;
i=0;
printf("Enter n=" );
scanf("%d", &n);
printf(" Enter Polynomial Coef and power=");
for(i=0;i<n;i++)
scanf("%d %d", &a[i].coef, & a[i].power);
printf("Enter x=" );
scanf("%d", &x);
for(i=0;i<n;i++)
{ sum=sum+a[i].coef*pow(x,a[i].power);
}
printf("Sum=%d\n",sum);
}
term a[100];
int startA, startB, finishA, finishB, avail, count=0;
int compare(int a, int b)
{ if(a>b)
return 1;
else
if(a<b)
return -1;
else
return 0;
}
void display()
{ int i=0, k;
printf(" Ist polynomial=\n");
for(;i<=finishA;i++)
printf("%d %d\n",a[i].coef,a[i].power);
printf(" IIst polynomial=\n");
for(;i<=finishB;i++)
printf("%d %d\n",a[i].coef,a[i].power);
printf(" \n \n Result polynomial=\n");
k=i;
for(k=i;k<avail;k++)
printf("%d %d\n",a[k].coef,a[k].power);
}
void polyadd()
{
int t, coeff;
avail=finishB+1;
printf("startA=%d startB=%d\n", startA, startB);
while(startA<=finishA && startB<=finishB)
{
t=compare(a[startA].power,a[startB].power);
printf("t=%d \n",t);
switch(t)
{
case -1 : attach(a[startB].coef, a[startB].power);
startB++; break;
case 0 : coeff=a[startA].coef+a[startB].coef;
attach(coeff, a[startA].power);
startA++; startB++; break;
case 1 : attach(a[startA].coef, a[startA].power);
startA++; break;
}
}
for(;startA<=finishA;startA++)
attach(a[startA].coef, a[startA].power);
for(;startB<=finishB;startB++)
attach(a[startB].coef, a[startB].power);
}
int main()
{ int i, n,m;
i=0; startA=0;
printf("Enter n=" );
scanf("%d", &n);
printf("Enter m=" );
scanf("%d", &m);
printf(" Enter Ist Polynomial Coef and power=");
for(i=0;i<n;i++)
scanf("%d %d", &a[i].coef, & a[i].power);
finishA=i-1; startB=i;
printf(" Enter Ist Polynomial Coef and power=");
for(;i<n+m;i++)
scanf("%d %d", &a[i].coef, & a[i].power);
finishB=i-1; avail=i;
polyadd();
display();
return 0;
}
Operations on Sparse Matrix: (i) Create (ii) Transpose (iii) Add (iv) Multiply
for(i=0;i<a[0].row;i++)
{
for(j=o;j<a[0].col;j++)
{
if(i==a[k].row && j==a[k].col)
{
printf("%d\t",a[k].value);
k++;
}
else
printf("0 \t");
}
}
printf("\n");
}
b[current].col=a[j].row;
b[current].value=a[j].value;
current++;
}
}
}
}
printf(" \n Input matrix\n\n");
for(i=0;i<=n;i++)
printf("%d %d %d\n",a[i].row,a[i].col,a[i].value);
Strcat(dest,char) :
This operation concatenates string string vhar into the end of the string dest.
int main()
{
char src[20],dest[20];
strcpy(src,”This is source”);
strcpy(dest,”This is destination”);
strcat(dest,src);
printf(“Final destination string is %s\n”,dest);
return (0);
}
Strlen(str) : This operation returns thr length of the entered string str.
int main()
{
char str[50];
int len;
printf(“Enter string”);
gets(str);
len=strlen(str);
printf(“Length of %s is %d\n”,str,len);
return (0);
}
Strcmp(s1,s2) :
This returns 0 if s1 and s2 are same, less than 0 if s1<s2, greater than 0 if s1>s2.
int main()
{
char s1[50],s2[50];
int ret;
printf(“Enter string s1”);
gets(s1);
printf(“Enter string s2”);
gets(s2);
ret=strcmp(s1,s2);
if(ret<0)
{
printf(“s1<s2”);
}
else if(ret>0)
{
printf(“s1>s2”);
}
else
{
printf(“s1=s2”);
}
Dr. Ganga Holi, ISE Dept., Global academy of Technology
10
Module I-Arrays, Strings,
return (0);
}
Strchr(s1,s2) :
This returns a pointer to the first occurrence of characterch in the string s1.
int main()
{
const char s1=’Tea & Biscuits’;
const char s2=’&’;
char ret;
ret=strchr(s1,ch);
printf(“String after %cis %s”,ch,ret);
return (0);
}
Strstr(s1,s2) :
Returns a pointer to the first occurrence of string s2 in string s1.
int main()
{
const char s1[50]=”Global Academy of Technology”;
const char s2[50]=”Academy”;
char ret;
ret=strstr(s1,s2);
printf(“The substring is %s\n”,ret);
return (0);
}
Char strncpy(dest,src)
This operation copies only ‘n’ characters from src string intp destination string and returns dest string.
Char strncat(dest,char) :
This concatenates dest and only n characters from src, returning in dest.
Strcmp(s1,s2,n)
This operation compares first ‘n’ characters of the string entered.
Q9. What do you mean by pattern matching? Where do we use this concept?
Pattern matching : A code to check if the given string is present in another string is pattern matching.
For example : “Global is present in Global Academy of Technology” . If the string is present then its
location is printed.
Assume that we have two strings, string and pat, where pat is a pattern to be searched. If pattern is present
in the string, then it returns its position else returns -1. it examines each character of the string until it
finds the pattern or it reaches the end of the string.
Example :
#include<stdio.h>
#include<string.h>
int match(char[],char[])
int main()
{
char a[100],b[100];
Dr. Ganga Holi, ISE Dept., Global academy of Technology
11
Module I-Arrays, Strings,
int position;
printf(“Enter text\n”);
gets(a);
printf(“Enter a string to find”);
gets(b);
position=match(a,b)
if(position!=-1)
{
printf(“Found at location %d\n”,position+1);
}
else
{
printf(“Not found”);
}
return (0);
}
int match(char text[],char pattern[])
{
int c,d,e,txt_length,pattern_length,position=-1;
txt_length=strlen(txt);
pattern_length=strlen(pattern);
if(pattern_length>txt_length)
{
return -1;
}
for(c=0;c<=txt_length-pattern_length;c++)
{
position=e=c;
for(d=0;d<pattern_length;d++)
{
if(pattern[d]==text[e])
{
e++;
}
else
{
break;
}
}
if(d==pattern_length)
{
return position;
}
}
return -1;
Dr. Ganga Holi, ISE Dept., Global academy of Technology
12
Module I-Arrays, Strings,
}
We can also embed a structure within a structure. For example, associated with our human structure, we
may wish to include the date of his or her birth.
typedef struct{
int month;
int day;
int year;
}date;
typedef struct
{
int age;
float salary;
char name[50];
date dob;
}human;
We can assign data to a structure variable as follows :
human person1, person 2;
person1.age=40;
person1.dob.month=10;
person1.dob.year=1997;
Unions : A union declaration is similar to a structure, but the fields of a union must share their memory
space. This means that only one field of the union is “active” at any given time.
typedef struct{
enum tagfield{female,male}gender;
union{
int children;
int beard;
}u;
}gendertype;
typedef struct{
char name[10];
int age;
float salary;
date dob;
gendertype genderinfo;
}human;
human person1;
person1.genderinfo.gender=male;
person1.genderinfo.u.children=4;
Self Referential Structures :
A self referential structure is one in which one or more of its components is a pointer to itself. Self
referential structures usually require dynamic storage management routines (malloc,free) to explicitly
obtain and release memory cinsider as an example.
Dr. Ganga Holi, ISE Dept., Global academy of Technology
14
Module I-Arrays, Strings,
typedef stuct{
char data;
struct list *link;
}list;
There the structure will have two components, data and link, Data is a single character, while link is a
pointer to a list structure.
list l1, l2, l3;
l1.link=l2.link;
Q11. What are pointers? How do we use pointers to different data types?
A pointer is a variable which contains the address in memory of another variable.
Declaration :
data_type *variable_name;
Ex : int *a;
Ex :
#include<stdio.h>
int main()
{
int var = 20;
int *ip;
ip=&var;
printf(“Address of variable is %x\n”, &var);
printf(“Address stored in ip variable is :%x”,ip);
printf(“value of *ip variable : %d”, *ip);
return 0;
}
Q12. Why do we need dynamic memory allocation techniques? Explain the functions
available for allocating memory dynamically.
Dynamic memory allocation : It refers to performing manual management for dynamic memory
allocation using standard library functions such as malloc, realoc, calloc and free.
The size of array initially declared can be sometimes insufficient or sometimes more than required but
dynamic memory allocation allows a program to obtain more memory space, while running or to release
space when not required.
Functions:
There are four standard library functions under “stdlib.h” for dynamic memory allocation.
malloc() – It allocates requested size of bytes and returns a pointer first byte of allocated space.
Syntax :
ptr=(data_type *)malloc(bysize);
Ex : (int*)malloc(100*sizeof(int));
calloc() – Allocates spaces for array elements, initializes to zero and then returns a pointer to memory.
Syntax : ptr=(data_type*)calloc(n,element_size);
Ex : ptr=(float*)calloc(25,sizeof(float));
realloc() – Changes the size of the previously allocated space according to the requirement.
Syntax : ptr=realloc(ptr,newsize);
free() – It deallocates the previously allocated space.
Syntax – free(ptr);
Sparse Matrix : If a matrix contains more zero entities then suc a matrix is called a sparse matrix.
050400
200010
050010
Ex:
500000
000010
[0 0 0 0 0 1 ]
The concept of sparse matrix is used in scientific or engineering applications.
Representation :
Array representation : 2D array having n-rows and 3-coloumns,where n is number of non-zero elements.
a[i][0] – represents row value
a[i][1] – represents column value
a[i][2] – represents matrix value
1 2 5
1 4 4
2 1 2
2 5 1
3 2 5
3 5 1
4 5 1
5 6 1
14. Define string. Explain string handling functions: strcat, strcpy, strcmp,
strncmp, strncat, strchr, strrchr, strtok, strstr, strspn, strcspn, strbrk
In C programming, array of character are called strings. A string is terminated by null character
/0. For example:
Dr. Ganga Holi, ISE Dept., Global academy of Technology
16
Module I-Arrays, Strings,
"c string tutorial"
Here, "c string tutorial" is a string. When, compiler encounters strings, it appends null character
at the end of string.
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char
type.
char s[5];
char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd"; OR, char c[5]="abcd"; OR, char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
char *c="abcd";
String variable c can only take a word. It is beacause when white space is encountered, the scanf()
function terminates.
#include <stdio.h>
int main()
{
char name[20];
Dr. Ganga Holi, ISE Dept., Global academy of Technology
17
Module I-Arrays, Strings,
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
Output
Here, program will ignore Ritchie because, scanf() function takes only string before the white
space.
#include <stdio.h>
int main()
{
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') // terminates if user hit enter
{
ch=getchar();
name[i]=ch;
i++;
}
name[i]='\0'; // inserting null character at end
printf("Name: %s",name);
return 0;
}
This process to take string is tedious. There are predefined functions gets() and puts in C language
to read and display string respectively.
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
Output:
string.h are:
L2=strlen(pat);
for(i=0;i<(L1-L2);i++)
{ j=0;
while( j! =L2 && text[i+j] ==pat[j])
{ j++;
}
If(j==L2)
{ flag=1; break;
}
}
If(flag==1)
printf(“pattern found”);
else
printf(“Not found”);
}
16. Write a program to search an element using linear and binary search.
Linear Search algorithm/function
Search(a, key)
{
For(i=0;i<n;i++)
{ if(a[i]==key)
{ flag=1; break;
}
}
If(flag==1) printf(“ Found”);
else printf(“not found”);
}
Binary search
Binsearch(a, key)
{ low=0; high=n-1;
mid=(low+high)/2
while(low<high && a[mid]!=key)
{
If(key<a[mid])
high=mid-1;
else low=mid+1;
mid=(low+high)/2;
}
if(a[mid]==key)
printf(“ found”);
else
printf(“Not found”);
}
*/ #include<stdio.h>
#include<conio.h>
#define SIZE 15
void create(int array[], int n)
{
int i;
printf(" Enter n elemnts\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
return ;
}
n--; return n;
}
int main()
{
int array[SIZE], n, choice, flag=0;
int position, value; int count=0;
char answer;
while(1)
{
printf("1. Create\n");
printf("2. Display\n");
printf("3. Inserting Elemnt at given valid position\n");
printf("4. Deleting an Element at a given valid Position(POS)\n");
printf("5. Exit\n");
printf("Enter choice =");
scanf("%d", &choice);
switch(choice)
{
case 1 : if(flag==0)
{
flag=1;
printf("Enter no. of elements=");
scanf("%d", &n);
// if n is > SIZE. Reduce n=SIZE
if(n>SIZE) n=SIZE;
create(array,n);
}
else
{
printf("Array is already created.cannot create again ");
}
break;
case 2 : display(array, n);
break;
case 3 : printf("Enter the location you wish to insert an element=\n");
scanf("%d", &position);
if(position>=SIZE || position>n+1)
{ printf("IT is not valid Position");
break;
}
printf("Enter the value to insert=\n");
scanf("%d", &value);
n=insertAtPos(array, n, position, value);
break;
case 4 : printf("Enter the location you wish to delete an element=\n");
scanf("%d", &position);
if(position>n)
{ printf("Postion is beyond the array element\n"); break;
}
if(n==0)
{
18. Write a program to sort the numbers using selection and bubble sort algorithms.
Ans:1) SELECTION SORT:
#include <stdio.h>
int main()
{
int array[100], n, i,j, position, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for ( i = 0 ; i< n ; i++ )
scanf("%d", &array[i]);
2)BUBBLE SORT:
#include <stdio.h>
int main()
{
int data[100],i,n,step,temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("%d. Enter element: ",i+1);
scanf("%d",&data[i]);
}
for(step=0;step<n-1;++step)
{ for(i=0;i<n-step-1;++i)
{
if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this line. */
{
temp=data[i];
data[i]=data[i+1];
data[i+1]=temp;
}
}
}
printf("In ascending order: ");
for(i=0;i<n;++i)
printf("%d ",data[i]);
return 0;
}
Questions on Module I
b. Consider the element B[3,3,3] in B. Find the effective indices E1, E2,E3
and the address of the element assuming Base(B)=400 and there are w=4
words per memory location(size of the data).