pavandm.files.wordpress.com · web viewconsider there are 2 programs p1.c and p2.c as shown. p1.c...
TRANSCRIPT
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Module-5: Pointers and Preprocessors, Introduction to Data StructuresPointers
Introduction to Pointers:
A pointer is very powerful feature of C language. It helps the programmers to
manipulate the data by using addresses of computer’s memories instead of identifiers. It
results into concise and efficient programming.
Definition
“A pointer is also a variable that holds only the addresses of other variables”
Declaration of Pointers
The pointers can be defined in the declaration part of the main( ) function by using
dereference operator(*). The syntax is as follow.
Syntax:
data_type * ptr_variable;
where,
data_type valid data types like int, float, char, struct type, etc.
* dereference operator
ptr_ variable valid identifier
Examples:
int n=7; /* integer variable */
int *ip; /* integer pointer*/ip=&n; /* address of ‘n’ will be stored in ip */
Variable n Pointer ip
Contents
7 Contents 0X800
Address 0X800 Address of pointer 0X1000
Note: 1. Assume address of ‘n’ is 0X800
2. Assume address of ‘ip’ is 0X1000
ip=0x800
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 1
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Examples to work with pointers:
1. To print address and contents of ‘n’ without using pointers.
printf(“Address of n = %d”,&n);
printf(“Contents of n=%d”,n);
o/p:
Address of n=0x800
Contents of n= 7
To print the address and contents of ‘n’ using pointers.
int n=7;
int *ip;
ip=&n;
printf(“Address of n = %d”,ip);
printf(“Contents of n=%d”,*ip); /* value at address 0x800*/
o/p:
Address of n=0x800
Contents of n= 7
2. float avg=88.88; /* variable of type float */
float *fp; /* pointer of type float*/
fp=&avg; /* address of n will be stored in fp*/
printf(“Address of variable avg = %d”,fp);
printf(“Contents of avg is %d = ”,*fp);
o/p:
Address of variable avg =0x2000
Contents of avg= 7
Advantages of using pointers:
1. Pointers can hold the addresses of other variables.
2. The use of pointers in programming results into concise and efficient programming.
i.e. program works with high speed
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 2
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
3. Dynamic Memory Allocation (DMA) is possible by using pointers. i.e. the required
number of memory blocks can be allocated neither more nor less. The process of
allocating the computer’s memory during program execution is called DMA.
4. Using pointers, programmers can construct Advanced Data Structures (ADTs) like
linked lists, queue, stack, tree, graph, set, etc. These ADTs are most commonly used
during the design and development of today’s real time applications.
5. The use of pointers with arrays, strings and user defined functions results into concise
and efficient programming.
Disadvantages of pointers:
1. Uninitialized pointers may create errors in program.
2. Pointer bugs (errors) are difficult to remove.
3. Dynamically allocated memory must be freed explicitly.
4. Pointers updated with incorrect values may lead to memory corruption.
Address Operator (&) and Dereference Operator(*)
To manipulate the data by using pointers, the C programmer makes the use of address
operator (&) and dereference operator (*).
& The ampersand sign is used as address operators. It helps the programmers to get the
addresses of other variables.
* The asterisk sign is used as deference operator. It helps the programmer to define
pointer variables and also to get the value at addresses.
e.g. To print the address and contents of ‘n’ using pointers.
int n=7; int *ip; ip=&n;
printf(“Address of n = %d”,ip);
printf(“Contents of n=%d”,*ip); /* value at address 0x800*/
o/p:
Address of n=0x800
Contents of n= 7
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 3
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Simple C-expressions using pointers:
The programmers can use pointers while writing C expressions to solve complex
problems. Some of the examples are as follow.
int n=7; /* normal variable */
int x, y; /* normal variables */
int *ip; /* pointer variable */
ip=&n; /* Address of n will be stored in ip */
*ip=17; /* is equals to n=17*/
x=*ip; /* is equals to x=17 */
y=*ip + 10; /* is equals to y=17 + 10 */
*ip = *ip + 5; /* is equals to n=n + 5 */
*ip*=10; /* is equals to n=n * 10 */
/* Programming example using pointers */#include<stdio.h>void main(){int n1,n2;int *ip1,*ip2;ip1=&n1;ip2=&n2;clrscr();printf("Enter two numbers:");scanf("%d%d",&n1,&n2);printf("\n Addition is %d",*ip1 + *ip2);if (*ip1>*ip2)printf("\n Largest number is %d",*ip1);elseprintf("\n Largest number is %d",*ip2);getch();}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 4
Output:Enter two numbers:7 3Addition is 10Largest number is 7
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Pointers and Functions Arguments (Call by address)
The call by reference method makes the use of pointers to pass the addresses
(references) of actual parameters to user defined function instead of values. In this method,
changes made to formal parameters will affect the actual parameters. This method is having
the capability to return multiple values back to called function, where as pass by value
returns only one value.
/* Example for call by reference or function to swap two values */#include<stdio.h>void swap(int *x,int *y);void main(){int x=7,y=3;clrscr();printf("\n Before swap or Before calling function \n");printf("\n x=%d y=%d \n",x,y);swap(&x,&y);printf("\n After Swap or After calling function \n");printf("\n x=%d y=%d \n",x,y);getch();}void swap(int *x, int *y){int temp;temp=*x;*x=*y;*y=temp;}
Pointers and Arrays
An array can be defined as a collection of logically related data elements of similar
type. The programmers can make the use of pointers with arrays to write efficient programs.
The programmers can increment / decrement the pointers to interact with the array elements./* Pointers and Arrays */#include<stdio.h>void main(){int a[5]={10,20,30,40,50};int *ip,i;ip=&a[0]; /* ip=a */clrscr();printf("The arrays elements:");for(i=0;i<5;i++){printf("\n%d",*(ip+i));}getch();}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 5
o/p:Before swapx=7 y=3After swapX=3 y=7
Output:The array elements:1020304050
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Increment/decrement pointers:
The pointer variables can be incremented or decremented to interact with next or
previous computers memory locations sequentially.
Whenever, we increment/decrement the integer pointer that will be incremented /
decremented by 2 because that occupies 2 bytes.
Whenever, we increment/decrement the float pointer that will be incremented / decremented
by 4 because that occupies 4 bytes.
Whenever, we increment/decrement the character pointer that will be incremented /
decremented by 1 because that occupies 1 byte./* Example for pointer increment */#include<stdio.h>void main(){int *ip;float *fp;char *cp;int i;clrscr();printf("\n integer pointer is incremented by 5 times \n");for(i=0;i<5;i++){printf("\t %d",ip+i); /* addition of 2 to address */}printf("\n float pointer is incremented by 5 times \n");for(i=0;i<5;i++){printf("\t %d",fp+i); /* addition of 4 to address */}printf("\n character pointer is incremented by 5 times \n");for(i=0;i<5;i++){printf("\t %d",cp+i); /* addition of 1 to address */}getch();}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 6
Output:
Good Morning
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Pointers and Strings:
The programmers can use while working with strings to write concise and efficient
programs.
Examples:/* Example for pointers and strings to display string on monitor by using pointer*/#include<stdio.h>void main(){char str[]="Good Morning";char *cp; /* character pointer*/int i; cp=&str[0]; /* address of first array element will be stored in cp */clrscr();while (*cp!='\0') /* value at first address not equals to NULL repeats */{printf("%c",*cp); /* prints value at address i.e. G and so on..*/cp++; /*pointer increments by 1 every time */}getch();}
Arrays of Pointers: Programmers can define arrays of pointers to store and process
addresses on ‘n’ number of variables while solving complex problems. It results into
efficient program.
Example: To store addresses of three variables x, y and z, you can define one pointer array of
the size 3.
int x, y, y;
int *ip[3];
ip[0]=&x, ip[1]=&y, ip[2]=&y;
Pointers to Pointers: While solving complex problems it is necessary for the programmer to
store and use the addresses of pointers and is possible by pointer to pointer.
Examples:
int n=7;
int *ip; /* pointer to normal variable n*/
int **ipp; /* it is the pointer to pointer to point ip */
ip=&n;
ipp=*ip;
Now, we display the contents of ‘n’ by using both pointer (ip) and pointer to pointer (ipp).
printf("\n n=%d",*ip); o/p: n=7
printf("\n n=%d",**ipp); o/p: n=7Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 7
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Memory Management (Allocation)
The programmer needs to allocate the computer’s primary memory to store and
process the data to solve a problem by using a computer. For this purpose, the programmer
makes the use of following two techniques.
i. Compile time or static memory allocation
ii. Dynamic or run-time memory allocation
Compile time memory allocation: As the name implies, the process of allocating the
computer’s primary memory well in advance before the execution of statements from
executable part of main() function in the declaration part is called compile time memory
allocation.
This technique has the following limitations.
The allocated memory is limited in size that cannot be varied during program
execution.
An array size must be defined with fixed size. i. e. size cannot be changed during
program execution.
Programmers cannot create Abstract Data Types (ADTs) like linked lists, trees and
graphs, etc.
All these limitations can be solved by using Dynamic Memory Allocation technique.
Dynamic or run-time memory allocation: The process of allocating the required number
of memory blocks during the program execution is called dynamic or run-time memory
allocation. This technique makes the use of memory allocating functions like malloc(),
calloc(), realloc() and free() with pointers.
Memory Allocation Functions: The alloc.h file is having number of memory allocating
functions. Some of the important are as follows.
1. malloc()
2. calloc()
3. realloc() and
4. free()
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 8
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
malloc() : It allocates the required number of memory blocks during the program execution
and returns the address of first memory block. The other addresses of next allocated memory
blocks can be obtained by addition operation with a pointer.
Syntax:
pointer=(data_type *) malloc(byte size);
where,
pointervalid pointer
data type the valid data type of which type memory could be allocated.
byte_size Total number of bytes. i.e. n * sizeof(data type)
In case of failure of memory allocation, the malloc() funcion returns NULL value.
Examples:
1. To allocate n number of memory blocks of integer type during program execution.
int *ip; /* integer pointer*/
int n;
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
ip=(int *) malloc(n*sizeof(int));
output:
Enter the value of n: 5
As per the given input 5, the 5 memory blocks of integer type will be allocated by
malloc() function and returns address of first memory block.
2. To allocate n number of memory blocks of float type during program execution.
float *fp; /* float pointer*/
int n;
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
fp=(float *) malloc(n*sizeof(float));
3. To allocate n number of memory blocks of char type during program execution.
char *cp; /* character pointer*/
cp=(char *) malloc(n*sizeof(char));/* Programming example for dynamic memory allocation by malloc */
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 9
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
/* To read and display n numbers by using pointers or DMA */#include<stdio.h>#include<conio.h>#include<alloc.h>void main(){int n,i,*ip;clrscr();printf("Enter the value of n: ");scanf("%d",&n);ip=(int *)malloc(n*sizeof(int));printf("\n Enter %d values ",n);for(i=0;i<n;i++){scanf("%d",(ip+i));}printf("\n The values are ");for(i=0;i<n;i++){printf("\t %d",*(ip+i));}getch();}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 10
Output:
Enter the value of n: 5
Enter 5 values
10 20 30 40 50
The values are
10 20 30 40 50
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
calloc() : It allocates the required number of memory blocks during the program execution
and returns the address of first memory block. The other addresses of next allocated memory
blocks can be obtained by addition operation with a pointer. The calloc() function initializes
the allocated memory blocks by Zero, whereas, the malloc() stores garbage values .
Syntax:
pointer=(data_type *) calloc (n, byte_size);
where,
pointervalid pointer
data type the valid data type of which type memory could be allocated.
n Number of memory blocks required
byte_size Total number of bytes.
In case of failure of memory allocation, the calloc() funcion returns NULL value.
Examples:
1. To allocate n number of memory blocks of integer type during program execution.
int *ip; /* integer pointer*/
int n;
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
ip=(int *) calloc (n, sizeof(int));
output:
Enter the value of n: 5
As per the given input 5, the 5 memory blocks of integer type will be allocated by
calloc() function and returns address of first memory block.
2. To allocate n number of memory blocks of float type during program execution.
float *fp; /* float pointer*/
int n;
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
fp=(float *) calloc (n, sizeof(float));
3. To allocate n number of memory blocks of char type during program execution. Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 11
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
char *cp; /* character pointer*/
cp=(char *) calloc (n, sizeof(char));
realloc(): This is another memory allocation function available in alloc.h. It helps the
programmer to allocate new memory space for the previously allocated memory by malloc()
or calloc().
Syntax:
pointer=realloc(pointer, new_size);
Example:
int *ip; /* integer pointer*/
int n;
printf(“Enter the value of n: ”);
scanf(“%d”,&n);
ip=(int *) malloc(n*sizeof(int));
printf(“\n %d memory blocks are allocated ”,n);
…
…
printf(“Enter the new value of n: ”);
scanf(“%d”,&n);
ip=realloc(ip, n*sizeof(int));
printf(“\n %d memory blocks are newly allocated ”,n);
output:
Enter the value of n: 5
5 memory blocks are allocated
Enter the new value of n: 7
7 memory blocks are allocated
free(): It de allocates the dynamically allocated memory by malloc() , calloc() or realloc()
functions. The programmer needs to de allocate the memory allocated by DMA (Dynamic
Memory Allocation) technique explicitly.
Syntax:
free (pointer);
Pointer to pointer:
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 12
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
The programmer can define and use pointer to pointer while creating complex abstract
data types (ADTs) while handling complex data. Pointer to pointer will hold the address of
another pointer.
Declaration of pointer to pointer: To define pointer to pointer, the programmer makes the use
of two de-reference operator (*) with data type. The syntax is as follows
Syntax:
data_type **pointer to pointer;
Example:
int n=7;
int *ip;
int **ipp;
ip=&n;
ipp=&ip;
/* programming example for pointer to pointer */
#include<stdio.h>
#include<conio.h>
void main()
{
int n=7; /* normal variable*/
int *ip; /* pointer */
int **ipp; /* pointer to pointer */
ip=&n;
ipp=&ip;
clrscr();
printf("\n Contents of n using pointer=%d",*ip);
printf("\n Contents of n using pointer to pointer=%d",**ipp);
getch();
}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 13
Output:
Contents of n using pointer= 7
Contents of n using pointer to pointer= 7
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Introduction to Preprocessor: Preprocessor is a program that processes preprocessing
statements of the source code before it passes through the compiler. It is a program that
accepts a source program with preprocessing statements as the input and produces another
source program which will not contain any preprocessing statements. The process of C
compilation is as shown in the figure.
Preprocessor Directives (Statements): Preprocessor directives or statements are the statements of C programming language which begins with # symbol.
Examples : #define , #include, #if, #endif , #ifdef and #else
Some of the important preprocessor directive are listed in table below :
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 14
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
The Preprocessor directives can be divided into following three categories
1. Macro Substitution directives
2. File Inclusion Directives
3. Compiler control directives
1. Macro Substitution Directives: Macro substitution is a process where an identifier in a
program is replaced by a predefined string composed of one or more tokens. The
preprocessor accomplishes this task under the directions of #define statement. This
statement usually known as a macro substitution directives (or simply a macro) takes the
following general form :
#define identifier token_string
Example :
#define COUNT 100
#define FALSE 0
#define PI 3.1412
#define START {
#define END }
#define EQUAL ==
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 15
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
#define NOT EQUAL !=
#define TRUE 1
#define FALSE 0
Programming Example : C Program to find the area of a circle#include <stdio.h>#include<conio.h>#define PI 3.1415 /* MACRO SUBSTITUTION DIRECTIVE*/ void main() { int radius; float area; clrscr(); printf("Enter the radius: "); scanf("%d",&radius); area=PI*radius*radius; printf("Area=%.2f",area);
getch();
}
2.
#include<stdio.h>#include<conio.h>#define MOD %#define EQUAL == void main( ){ int n; printf(“Enter one number\n”); scanf(“%d”,&n); if(n MOD 2 EQUAL 0) printf(“ The given number is even\n”); elseprintf(“The given number is odd\n”);getch();}
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 16
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
2. File Inclusion Directives: An external file containing functions or macro definitions can
be included as a part of a program so that we need not rewrite those functions or macro
definitions. This is achieved by the preprocessor directives: #include <filename>
Example :#include<stdio.h> . Here, "stdio.h" is a header file and the preprocessor replace
the above line with the contents of header file.
Other Examples : #include<conio.h> , #include ”TEST.C” ,
#include “SYNTAX.C” , etc.
Example : Program to illustrate the use of #include directiveConsider there are 2 programs p1.c and p2.c as shown
p1.c p2.c
p2.c includes p1.c
H/W: To find cube of given number as shown in above example
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 17
int square(int x){Return(x*x);}
#include<stdio.h>#include<conio.h>#include “p1.c”void main( ){int x,sq=0;printf(“Enter one number\n”);scanf(“%d”,&x);sq=square(x);printf(“Square of given number=%d”,sq);getch();}
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
3. Compiler Control Directives: These are used to execute or define macros based on given
condition. The Programmers can write portable programs by using these directives
Examples
Directives Functions
#ifdef It test for macrodefinition
#endif End of #if
#ifndef Test whether the macro is defined or not
#if Test the compile type condition
#else Alternative for #if
#elif elseif sequence
Write a C program to print the double and triple of given number using preprocessor
directives
#include<stdio.h>#include<conio.h>#define DOUBLE (2*n)#define TRIPLE (3*n) void main( ){ int n,du,tri; printf(“Enter one number\n”); scanf(“%d”, &n); du=DOUBLE(n); tri=TRIPLE(n); printf(“Double of given number=%d”,du); printf(“Triple of given number=%d”,tri);getch();}
Write a C Program to SWAP two values using Preprocessor directives#include<stdio.h>#include<conio.h>#include SWAP(a,b,temp) (temp=a, a=b, b=temp); void main( ){ int a=10, b=20, temp=0; SWAP(a,b,temp)Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 18
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
printf(“ After swapping a=%d b=%d”, a,b);getch( );}
Introduction to Data Structure
As we know, the programmers make the use of different data types (data structures) to
read input data, process and to display processed data on screen. The programmers make the
use of following data types to store and process different data.
i. The C programmer makes the use of built-in data types (data structures) like int,
float, double and char to store and process simple data like integers, floating point
numbers, double type of value and character type of data.
ii. The C programmer makes the use of derived data types like array, structure and
union to store and process large volume of data of similar and dissimilar type.
iii. The C programmer makes the use of Abstract Data Types (ADTs) like stack,
queue, linked list, tree and graph, set, etc. to store and process more complex data.
Data Structure: “Data structure can be defined as a way of organizing complex and large
volume of data in computer’s memory in such a way that, which can be processed
efficiently”
The defined data structure must have the following characteristics.
A data structure should be able to process large volume of data using less computer’s
memory.
A data structure must be capable to represent desired relationship between individual
data elements.
It should provide provision to access the data elements randomly.
The insertion, deletion and modification of data elements should be easier.
The re-arrangement of data elements should be easier.
It should provide efficient search operation.
It should provide efficient mechanism for data traversal i.e. visiting each data element
to perform desirable operations.Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 19
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Types of Data Structures: The data structures can be mainly classified into following two
types.
1. Primitive data structures
2. Non primitive data structures
a. Linear data structures
b. Non-linear data structures
1. Primitive data structures: These are the basic or built-in or fundamental data structures
like int, float, double and char. These are designed and developed by developers of C
compiler to store and process simple data.
2. Non primitive data structures: The non primitive data structures are designed and
created by C programmers while processing complex data. The examples for non primitive
data structures are stack, queue, linked list, tree, graph and set etc. These are sub classified
into following two types.
a. Linear data structure: The data structure that helps to store and process data sequentially
inside the computer’s memory are called linear data structures.
e.g. array, stack, queue and linked list.
b. Non-linear data structure: The data structure that helps to store and process data with
complex relationship between them are called non-linear data structures.
e.g. trees, graphs and sets.
Stack: A stack is a very simple single ended data structure. It permits the programmer to
add and delete the data elements from only one end i.e. from top of the stack. Thus, the data
elements inserted at the last can be retrieved first. Hence, a stack is also called as a Last In
First Out (LIFO) data structure.
Operations on a stack:
The following simple operations can be performed on stacks.
Creating a stack: Stack can be created by creating an array of size N or by using pointers.
Push: The insertion of new element into the stack and is called push operation.
Pop: The deletion of existing element from its top is called pop operation.
Peek: The view or accessing the top element from the stack is called peek operation.
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 20
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Stack overflow: If, we attempt to add new element to full stack then stack overflow takes
place.
Stack underflow: If, we attempt to remove element from empty stack then stack underflow
takes place.
Example: Creating a stack by using an array to store 5 data elements of integer type.
int stack[5];Empty stack Push(10) Push (20) Full Stack Pop operation(50)4 4 4 4 50 43 3 3 3 40 3 402 2 2 2 30 2 301 1 top=1 20 1 20 1 200 top=0 10 0 10 0 10 0 10
top=-1
The stack can be implemented by using global type of an array.
1. Creating a stack to store and process maximum 10 data elements of integer type.
# define MAX_SIZE 10
int stack[MAX_SIZE];
int top=-1; /* empty stack*/
2. Implementation of push operationvoid push (int data){ if (top>=MAX_SIZE-1) { printf(“\n Error! Stack overflow!”); getch(); exit(); }stack[++top];}
3. Implementation of pop operationint pop()
{
if (top<0)
{
printf(“\n Error! Stack underflow!”); getch(); exit(); }return stack[top--];
}
4. Implementation of peek operationint peek()
{
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 21
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
If (top<0)
{
printf(“\n Error! Empty stack!”); getch(); exit(); }
return stack[top];
}
Applications of stack:
Stack data structure can be used in the development of those applications in which
Last In First Out operations are required. They are as follows
Implementing applications that include recursion.
String reversal
Conversions of mathematical expressions between various forms like infix, prefix and
postfix.
To balance the parentheses of an expression.
Queue: A queue is a double ended data structure. It has two ends named front and rear. It
mimics the behavior of a queue of persons at reservation counter, ticket counter, in banks,
etc. In this data structure, the new data element is inserted from the rear end and deleted from
the front end of a queue. i.e. an element inserted first in the queue is removed first from the
queue. Thus, queue is also called as First In First Out (FIFO) data structure.
Front end 10 20 30 40 50 rear end
-1 0 1 2 3 4
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 22
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Operations on a queue:
The following simple operations can be performed on queues.
Creating a queue: Queue can be created by creating an array of size N or by using pointers.
INSERT FROM REAR END : The insertion of new element into the queue from rear end.
It is called enqueue operation.
DELETE FROM FRONT END : The deletion of existing element from the front end. It is
called dequeue operation.
DISPLAY ELEMENTS: The viewing of front element from a queue is called peek
operation.
Types of Queue
1) Normal QueueFront end 10 20 30 40 50 rear end
2) Circular Queue Rear End Front End
3) Double Ended Queue(dequeue)
Applications of Queue:Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 23
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
In operating systems, for controlling access to shared system resources such as printers, files, communication lines, disks and tapes.
For simulation of real-world situations--- Ex: Banking Systems etc.
Applications of queues are used in Print Spooler .
MP3 players and Portable CD players are implemented using queue concepts.
Linked List: A linked list is a data structure which is collection of zero or more nodes with each node consisting of two fields data and link. The data field holds actual information that has to be processed . Link fields contains the address of next node. It is pictorially represented as shown below
NODE= data + link
Address of next node
Each Node contains 2 fields
Data:- This field stores actual data or information.
Link:- Link field contains address of next node.
Different types of Linked List
Singly linked list.
Doubly linked list.
Circular singly linked list.
Circular doubly linked list.
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 24
Data Link
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Singly Linked List: A singly linked list is a linked list, where each node has data and link field. If there exists only one link field in each node of the list, the linked list is called as singly linked list.
The pictorial representation of linked list consisting of 50, 20, 45, 10 and 80 is as shown below
1001 1020 1008 1012 1010
Data Link Data Link Data Link Data Link Data Link
Node= data+link
The pointer First contains the address of the first node using which we can access any nodes in the list.
In above picture the list contains 5 nodes each consists of 2 fields data and link .
In the first field data which contains actual information or data i.e. 50, 20, 45, 10 , 80.
The second field link contains address of next node . The arrow indicates that the
address of next node stored in link field of previous node.
Basic Operations of Linked List:
1) Inserting a node into the list
2) Deleting a node from the list.
3) Search in list
4) Reverse the list
5) Display the contents of the list.
Explain it by your own….
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 25
50 20 45 10 80
First
‘\
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Doubly Linked List: A doubly list is a linked list where each node is divided into 3
parts.
Data: This field contains actual information or value.
Rlink: This is a field which contains address of the right node( Next node).
Llink: This is a field which contains address of left node( Previous Node).
Llink Data Rlink
Node=Llink+Data+Rlink
Pictorially it is represented as follows
Llink Data Rlink
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 26
10 20 30 40
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Applications of Linked List:
1] Very long numbers of more than 100 digits can be added very efficiently using linked list.
2] Polynomial addition, subtraction, multiplication can be done very easily using linked list.
3] Linked list applications are used in dictionary.
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 27
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Trees: A tree a non-linear data structure where it a collection of nodes. Each nodes are
arranged in hierarchical order (in sorted order). Each nodes are connected with edges without
having any cycle.
Top node in the tree is called is root.
A part of tree which is connected to left of root is called as left sub tree.
A part of tree which is connected to right of root is called as right sub tree.
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 28
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Binary Tree: It is a tree in which each parent node has at most 2 child nodes. That means
each nodes has either zero, one or two child nodes. If the node has more 2 child nodes then it
is not called as binary tree.
Here A is root node/parent node. B and C are child node for A.
B-D-E is called as left sub tree as it is connected to left side of root. C-F-G is called as right
sub tree as it is connected to right side of root.
Tree Traversal Methods: A tree can be traversed in 3 different ways
1] Preorder Traversal
2] Inorder Traversal
3] Postorder Traversal
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 29
B.L.D.E.A’s Vachana Pitamaha Dr. P. G. Halakatti College of Engineering & Technology, Vijyapur-03.
Preorder Traversal : The steps of this tree traversal technique is as follows.
Step 1) Process Root node.
Step 2) Traverse left sub tree.
Step 3) Traverse right sub tree.
Inorder Traversal : The steps of this tree traversal technique is as follows.
Step 1) Traverse left sub tree.
Step 2) Process the Root node.
Step 3) Traverse right sub tree.
Preorder Traversal : The steps of this tree traversal technique is as follows.
Step 1) Traverse left sub tree.
Step 2) Traverse right sub tree.
Step 3) Process the Root node.
Department of Computer Science and Engineering Class Notes By Mr. P.D.Mahendrakar Asst. Prof. Page| 30