Module 1 - DS
Module 1 - DS
Module 1 - DS
Introduction:
Mrs.Mithuna H.R
Assistant Professor
Department of ISE
Acharya Institute Of Technology
Data item: A data item refers to a single unit of value. For eg. roll no of a student,
marks, name of an employee, address of person etc. are data items. Data items
that can be divided into sub items are called group items (Eg. Address, date,
name), where as those who can not be divided in to sub items are called
elementary items (Eg. Roll no, marks, city, pin code etc.).
B 18 M 109ee1234 ISE
Here, it is an example of student details where STUDENT is the given entity. Then
name, age, Gender, roll number, branch are attributes and their values are
properties (A, 17, M, 109cs0132, CSE). Collection of student details is student
entity set and Roll number is the primary key which uniquely indicates each
Department of ISE Acharya Institute of Technology
student details.
Why Data Structure
•Human requirement with computer are going to complex day by day. To solve
the complex requirements in efficient way we need this study.
• Provide fastest solution of human requirements.
• Provide efficient solution of complex problem.
–Space
– Time
• Insert (PUSH)
• Delete(POP)
• Overflow
• Underflow
scanf("%d",&val); val=2
for(i=n-1;i>=pos;i--) 3>=1
2>=1
1>=1
0>=1
i=3
i=1
i=0
i=2
{
a[i+1]=a[i]; a[4]=a[3]
a[3]=a[2]
a[2]=a[1]
}
a[pos]=val; n=4+1=5
a[1]=2
n=n+1;}
Department of ISE Acharya Institute of Technology
}
Function to Delete an item at specified position
void delete() n=4
{
i-> 0 1 2 3
printf("\nEnter the position of the element to be deleted:\t");
a 1 2 3 4
scanf("%d",&pos); pos=1
i-> 0 1 2 3
val=a[pos]; val=a[1] val=2
a 1 3 3
4 4
for(i=pos;i<n-1;i++)
i=1
i=2
i=3
1<3
2<3
3<3 i-> 0 1 2
{
a 1 3 4
a[i]=a[i+1];
a[1]=a[2]
a[2]=a[3]
}
n=n-1; n=4-1=3
Declaration: The syntax is same as for 1-D array but here 2 subscripts
are used.
Syntax:data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows Columnsize specifies the no.of
columns.
Example: int a[4][5];
Char a[5][11]={
“DHARMARAYA”,
“BHIMA”,
“ARJUNA”,
“NAKULA”,
“SAHADEVA”
}
0 1 2 3 4 5 6 7 8 9 10
0 D H A R. M A R A Y A \0
1 B H I M A \0
a 2 A R J U N A \0
3 N A K U L A \0
4 S A H A D E V A \0
STRING OPERATIONS
C supports a wide range of built in functions that manipulate null-terminated
strings :− strcpy(s1, s2):- Copies string s2 into string s1.
strcmp(s1, s2):- Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
strrev(s1):-This function reverses all characters in the string str except the
terminating NULL character ‘\0’.
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
The syntax to use strcpy() is
void main() Void main()
strcpy(char dest[], char src[]) { {
•The function strcpy copies the contents of source string src to destination dest
char src[]=“RAMA”; char src[20];
char dest[6]; char dest[20];
including ‘\0’.
•So, the size of destination string dest should be greater or equal to the size of strcpy(dest,src); int i = 0;
printf(“Enter the string\n”);
source string src. printf(“Dest string = %s\ gets(src);
n”,dest);
dest src dest src
} while( src[i] != '\0’)
0 0 dest[0]= src[0] {
R R dest[i]=src[i];
1 1 dest[1]= src[1] i + +;
A A INPUT }
2 2 dest[2]= src[2] RAMA dest[i]=‘\0’;
M M
3 3 dest[3]= src[3]
A A OUTPUT printf(“Dest String = %s\
4 4 Dest string = RAMA n”,dest);
\0 \0 }
In general, dest[i]=src[i] INPUT
Enter the string
where initial RAMA
value
. of i=0 OUTPUT
Dest string = RAMA
Write a C program to copy string src to string dest without using built-in function.
#include<stdio.h>
void strcopy(char src[],char dest[])
{
int i=0;
void main()
while(src[i]!='\0')
{
{
char s1[20],s2[20];
dest[i]=src[i];
printf("Enter a string : ");
i++;
gets(s1);
}
strcopy(s1,s2);
dest[i]=’\0’;
printf("Given string : %s\n",s1);
}
printf("Copied string : %s\n",s2);
}
#include<stdio.h> #include<stdio.h>
The syntax to use strlen() is #include<string.h> #include<string.h>
Void main()
void main() {
strlen(str)
{ char str[20];
•This function returns the length of the string str i.e. it counts all the characters char str[]=“RAMA”; int i = 0;
up to ‘\0’ except ‘\0’. printf(“Length = %d\ printf(“Enter the string\n”);
•So, an empty string has length zero. n”,strlen(str)); gets(str);
i=0; A I T \0
} while( str[i] != '\0’)
Consider the string “ACIT”
{
str OUTPUT i + +; \\0 1 2 3
Length=4 }
printf(“Length = %d\n”,i); //3
}
A C I T \n
i 0 1 2 3 4 INPUT
AIT
i=0;
while(str[i]!=‘\0’) OUTPUT
i++ Length=3
.
4)Write a C program to find string length without using built-in function.
#include<stdio.h>
int strleng(char s1[])
{
int i=0; void main()
while(s1[i]!='\0') {
i++; int len;
return i; char s[20];
} printf("Enter a string : ");
gets(s);
len=strleng(s);
printf("The length of the string : %d.",len);
}
.
5)Write a C program to reverse a given string without using built-in function.
#include<stdio.h>
void str_rev(char src[],char dest[])
{
int i,n=0; void main()
while(src[n]!='\0') {
n++;
for(i=0;i<n;i++) char src[20],dest[20];
{ printf("Enter a string1 : ");
dest[n-1-i]=src[i]; gets(src);
} str_rev(src,dest);
dest[n]=’\0’; printf("The reversed string : %s",dest);
} }
There are two ways of passing parameters to the functions Calling function Called function
#include<stdio.h> Void exchange(int a,int b)
•Pass by value (also called call by value)
•Pass by reference (also called call by reference) Void exchange(int m, int n); {
int temp;
Pass by value (call by value) void main() printf(“Before exchange\n”);
{ printf(“m=%d and n=%d\
•When a function is called with actual parameters, the values of actual int a,b; n”,a,b);
parameters are copied into formal parameters. a=10, b=20;
printf(“Before exchange”); temp=a;
•If the values of the formal parameters changes in the functions, the values of printf(“a=%d and b=%d\ a=b;
the actual parameters are not changed. n”,a,b); b=temp;
•This way of passing parameters is called pass by value or call by value
exchange(a,b); printf(“After exchange\n”);
printf(“a=%d and b=%d\
printf(“After exchange”); n”,a,b);
printf(“a=%d and b=%d\
n”,a,b);
} }
OUTPUT Before exchange
Before exchange
m=10 and n=20
a=10 and b=20
. After exchange
After exchange
•In pass by reference, a function is called with addresses of actual parameters. Calling function Called function
•In the function header, the formal parameters receive the addresses of actual #include<stdio.h> Void exchange(int *m,int *n)
parameters. Void exchange(int *m, int *n); {
int temp;
•Now, the formal parameters do not contain values, instead they contain
void main() printf(“Before exchange\n”);
addresses.
{ printf(“m=%d and n=%d\
•Any variable if it contains an address, it is called a pointer variable. int a,b; n”,*m,*n);
a=10, b=20;
•Using pointer variables, the values of the actual parameters can be changed. temp=*m;
printf(“Before exchange”); *m=*n;
•This way of passing parameters is called Pass by reference or call by printf(“a=%d and b=%d\ *n=temp;
reference. n”,a,b);
printf(“After exchange\n”);
exchange(&a,&b); printf(“m=%d and n=%d\
n”,*m,*n);
printf(“After exchange”);
printf(“a=%d and b=%d\ }
n”,a,b);
}
Before exchange
OUTPUT
Before exchange m=10 and n=20
.
a=10 and b=20 After exchange
After exchange
m=20 and n=10
Comparison of Pass by Value and Pass by Reference
1 Values of variables are passed in the function call. Addresses of the variables are passed in the function
call.
2 The type of actual and formal parameters must be same. The type of actual and formal parameters must be
same and the formal parameters must be declared as
pointers.
3 Formal parameters contain the values of actual Formal parameters contain the addresses of actual
parameters. parameters.
4 The actual parameters are not changed when the formal The actual parameters are changed when the formal
parameters are changed. parameters are changed.
5 Less information transfer. Only one value can be More information transfer as changes made to formal
returned. parameters change actual parameters.
Functions returning pointers /* Pointer to pointer */
•A function can return a single value using return statement or multiple values
It is possible to make a pointer to point to another pointer variable.
using pointers in parameters. A variable which contains address of a pointer variable is called pointer
•Since pointer is also a data type in C, we can return a pointer from a function.
to pointer.
.
Arrays and pointers:
Traversing an array by using pointers
int arr[5] = { 10, 20, 30, 40, 50};
arr=1000
10 20 30 40 50 #include <stdio.h>
int main()
{
int i,sum,*p;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
*p; return 0;
p=x; is equal to p=&x[0]; }
Now we can access every value of x using p++ to move from one element to
another.
p=&x[0](=1000)
p+1=&x[1](=1002)
p+2=&x[2](=1004) OUTPUT:
p+3=&x[3](=1006) 1
p+4=&x[4](=1008) 2
3
. 4
5
Pointers can be used to manipulate two – dimensional arrays as well . Pointers and Character Strings
C supports an alternative method to create strings using
One dimensional array x, the expression.
* (x+i) or *(p+i) = x[i]
pointer variables of type char.
char *str=“good”;
Two dimensional array can be represented by the pointer expression as follows: The pointer str now points to the first character of the string
“good: as
*(*(a+i)+j) or *(*(p+i)+j) g o o d
10 and 15
The sum is 25
.
Pointers and Structures /*Write a program to illustrate the use of structure pointer
The name of an array stands for the address of its zeroth element. */
The same thing is true of the name of arrays of structure variables.
Suppose product is an array variable of struct type.
struct invent
The name product represents the address of its zeroth element.
Consider the following declaration: {
struct inventory char name[30];
{ int number[30];
char name[30]; float price;
int number[30];
};
float price;
}product[2],*ptr;
ptr=product; main()
{
Its members can be accessed using the following struct invent product[3],*ptr;
ptrname
printf(“INPUT \n\n”);
ptrnumber
ptrprice
for(ptr=product;ptr<product+3;ptr++)
scanf(“%s%d%f”,ptrname,&ptrnumber,&ptrprice);
}
Memory Allocation
Static Memory Allocation
•It is a process where in the memory space is allocated during the
compilation time.
•Here the allocated memory space cannot be expanded or reduced to
accommodate more or less data, i.e. the size of the allocated memory space
is fixed and it cannot be altered during execution.
During compilation, the compiler will allocate 10 memory locations for the
variable ‘a’ and once defined cannot be changed.
During execution we cannot have more than 10 data items, and if we use 3
locations, another 7 locations are wasted.
It is the process of allocating memory space during run time. This type of
requirement is unpredictable.
The following are the functions using which additional memory space can be
storage space.
2 The size of the allocated memory space is fixed and The size of the allocated memory space is not
it cannot be altered during execution. fixed and it can be altered (increased / decreased)
during execution.
3 This type of memory allocation can be used in This type of memory allocation can be used in
applications where the data size is fixed and known applications where the storage requirement is
before processing. unpredictable.
4 Execution is faster because memory is already Execution is slower because memory is has to be
allocated and only data manipulation is done. allocated and only then data manipulation is done.
5 Part of memory allocated is stack memory or Part of memory allocated is heap memory
global/static memory.
6 Ex: arrays Ex: Dynamic arrays, linked lists
of int is reserved and the address of the first byte of the memory allocated is
allocated block of memory. On failure i.e. if the specified size of memory is not
of 200 int (array of 200 integers) is reserved and the address of the first byte
•The storage space allocated dynamically has no name and therefore its
•In case of realloc( ), the contents of the old block will be copied into the
newly allocated space and so, this function guarantees that the earlier
2 Allocates a block of memory of specified size. Allocates multiple blocks of memory, each block
with same size.
3 Allocated space will not be initialized. Each byte of the allocated space is initialized to
zero.
4 Since no initialization takes place, time efficiency is calloc( ) is computationally more expensive because
higher than calloc( ) of zero filling but, occasionally, more convenient
than malloc( )
5 This function can allocate the required size of memory This function can allocate the required number of
even if the memory is not available contiguously but blocks contiguously. If the required memory cannot
available at different locations. be allocated contiguously, it returns NULL.
#include<stdio.h>
#define MALLOC(p,n,type)\ main()
{
p=(type*)malloc(n*sizeof(type));\ int *p1,*p2;
int sum;
if(p==NULL)\ MALLOC(p1,1,int);
{\ MALLOC(p2,1,int);
#include<stdio.h>
#define CALLOC(p,n,type) \ main()
{
p=(type*)calloc(n,sizeof(type)); \ int *p1,*p2;
int sum;
if(p==NULL)\ CALLOC(p1,1,int);
{ \ CALLOC(p2,1,int);
*p1=10;
printf(“Insufficient memory\n”); \ *p2=20;
sum=*p1+*p2;
exit(0); \ printf(“%d+%d=%d\n”,*p1,*p2,sum);
}
}
#include<stdio.h>
#define REALLOC(p,n,type) \ void main()
{
p=(type*)realloc(p,n*sizeof(type)); \
Char *str;
if(p==NULL) \ str=(char*)malloc(15);
strcpy(str,”information”);
{ \ printf(“string=%s\n”,str);
REALLOC(str,60,char);
printf(“Insufficient memory\n”); \ strcpy(str,”information science and
Engineering”);
exit(0); \ printf(“string=%s\n”,str);
}
}
In general
MALLOC(x,rows,int*); //rows-represents number of rows in a two dimensional array
Department of ISE Acharya Institute of Technology
Stage 2: Allocate memory for each row with specified number of column .
Example: Allocate memory for 5 columns with respect to row x[0],x[1] and x[2]
using MALLOC() three times as shown below.
An array item can be accessed by using its Structure items can be accessed using ‘.’or
subscript or by using dereferencing / by using –> for pointers.
indirection (*) operator for pointers.
cf px