0% found this document useful (0 votes)
180 views77 pages

18CSC162J DSA Unit1

This document provides information about the "Data Structures and Algorithms" course offered at SRM Institute of Science and Technology, Chennai. The purpose of the course is to utilize different data types, searching and sorting algorithms, linked lists, stacks, queues and trees for real-time application development. By the end of the course, students will be able to identify different data structures, create algorithms for searching and sorting, construct various data structures and evaluate their operations. Topics covered include introduction to data structures, arrays, linked lists, stacks, queues, trees, graphs, and hashing.

Uploaded by

Zaidali 050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views77 pages

18CSC162J DSA Unit1

This document provides information about the "Data Structures and Algorithms" course offered at SRM Institute of Science and Technology, Chennai. The purpose of the course is to utilize different data types, searching and sorting algorithms, linked lists, stacks, queues and trees for real-time application development. By the end of the course, students will be able to identify different data structures, create algorithms for searching and sorting, construct various data structures and evaluate their operations. Topics covered include introduction to data structures, arrays, linked lists, stacks, queues, trees, graphs, and hashing.

Uploaded by

Zaidali 050
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

SRM

INSTITUTE OF SCIENCE ANDTECHNOLOGY,


CHENNAI.

DATA STRUCTURES AND ALGORITHMS


(18CSC162J)

Dr. K.Vijaya
Associate Professor
Department of CSE
SRMIST/KTR
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Learning The purpose of learning this course is to:


Rationale
1 Utilize the different data types; Utilize searching and sorting algorithms for data
search
2 Utilize linked list in developing applications

3 Utilize stack and queues in processing data for real-time applications

4 Utilize tree data storage structure for real-time applications

5 Utilize algorithms to find shortest data search in graphs for real-time application
development
6 Utilize the different types of data structures and its operations for real-time
programming applications
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Learning At the end of the course learners will be:


Outcome
1 Identify linear and non-linear data structures. Create algorithms for searching and
sorting
2 Create the different types of linked lists and evaluate its operations

3 Construct stack and queue data structures and evaluate its operations

4 Create tree data structures and evaluate its types and operations

5 Create graph data structure, evaluate its operations, implement algorithms to identify
shortest path
6 Construct the different data structures and evaluate their types and operations
SRM
INSTITUTE OF SCIENCE ANDTECHNOLOGY,
CHENNAI.

INTRODUCTION TO DATA
STRUCTURES
UN I T 1
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
TOPICS TO BE COVERED (THEORY)
Session Topics
1 Introduction to Data Structure
2 ADT and operations
3 Specifications of Algorithms, recursion and performance analysis
4 Style of programming, refining code and Complexity (Space and Time)
5 Mathematical notations and functions
6 Asymptotic notations – Big O, Omega and Theta
7 Data Structure : Types – Linear and Non Linear
8 1D and 2D Array using Pointers – Initialize and access
9 Structures and Array of Structures
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

TOPICS FOR LAB SESSION

Session Topics
1 Recursive functions
2 Towers of Hanoi
3 Array implementation using pointers - Insertion
4 Array implementation using pointers- Deletion
5 Structures using pointers
6 Array of structures using Pointers
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ELAB SESSIONS

1. SEARCHING
2. SORTING
3. ARRAYS
4. LINKED LIST
5. STACK
6. QUEUE
7. TREE1
8. TREE2
9. GRAPH
10. HASHING
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

LEARNING RESOURCES

• Fundamentals of Data Structures, E. Horowitz and S. Sahni, 1977.


• Data Structures and Algorithms, Alfred V. Aho, John E. Hopperoft, Jeffrey D. UIlman.
• Mark Allen Weiss, Data Structures and Algorithm Analysis in C, 2nd ed., Pearson Education,
2015
• Reema Thareja, Data Structures Using C, 1st ed., Oxford Higher Education, 2011
• Thomas H Cormen, Charles E Leiserson, Ronald L Revest, Clifford Stein, Introduction to
Algorithms 3rd ed., The MIT Press Cambridge, 2014
INTRODUCTION
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

PROBLEM SOLVING

• Process
Creative Thinking (Generate)
• Defining the Problem Critical Thinking (Judge)
• Designing the Solution
• Implementing
• Testing
• Documenting and Maintaining
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

CREATIVE VS CRITICAL

• Pose questions • Pose questions


• Imagine possibilities • Consider perspectives
• Brainstorm solutions • Identify pros and cons
• Elaborate • Determine causes
• Improvise • Predict effects
• Speculate • Consider alternatives
• Use Intuition • Avoid assumptions
• Defer Judgements • Draw conclusions
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STEPS TO SOLVE PROBLEM USING
PROGRAMMING
• Understand the problem correctly
• Read more than once
• Explain to someone else
• Ask related question
• Analyze, divide and Assess
• Analyse and process information about the problem
• Break it, if necessary
• Try to solve manually and note the steps
• Fine tune the steps by using sample inputs
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STEPS TO SOLVE PROBLEM USING
PROGRAMMING
• Optimize the step
• Consider the steps written for specific samples and generalize it
• Try to eliminate steps that are repeated
• Write Pseudo code
• Based on the steps derived ensure that you write pseudo code and
check for correctness of Logic
• Write Program
• Choose a programming and convert the pseudocode into a program
• Optimize code
• Use programming language construct to optimize the code
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
PROBLEM SOLVING THROUGH
PROGRAMMING
• Analyze
• Design – Analyze – Resource and Accuracy
• Implementation – Analyze – Accuracy
• Testing/ Debugging
• Maintenance
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

PROPERTIES

Mistakes in resource management and logic errors


• Reliability Conceptual correctness of algorithms
• Robustness Errors like incorrect/corrupt data, unavailability of resources, power outage

• Usability Ease with which it could be used – User Interface


• Portability Range of hardware/operating environment

• Maintainability Ease with which it could be modified – fix bugs, security holes, adapt to new environment
• Efficiency/Performance

System resources that are consumed: Processor time, Memory Space, Disks, Network bandwidth
SRM
The data structures deal with the study of how the data is
organized in the memory, how efficiently it can be
INSTITUTE
retrieved OF SCIENCE
and manipulated and theAND TECHNOLOGY,
possible ways in which
CHENNAI.
different data items are logically related”.

DEFINITIONS

• Datum is a single value of a variable.


• Data are a set of values of qualitative or quantitative variables
about one or more persons or objects,
• Data Structure is a collection of data values, the relationships
among them, and the functions or operations that can be applied
on the data.

• Organise, store, manipulate and retrieve data in the computer


efficiently
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
FieldsCHENNAI.

Field TERMINOLOGIES
Name Register No Branch Batch
• Field (Attribute):
Name Register No Branch Batch
Anjali RA201106 CSE 2011
Record
• Record (Structure)
Name Register No Branch Batch
Student Anjali RA201106 CSE 2011
• Data set (Entity) Alamu RA201007 CE 2010
Student • Data base
Courses
(Entity
Registered
set) Malathi RA201009 CE 2010 Courses
Name Register No Branch Batch Register No Sem Course code Code Name
Anjali RA201106 CSE 2011 RA201007 5 CE501 CE501 Foundation Engg.
Alamu RA201007 CE 2010 RA201007 5 CE502 CE502 Reinforced concrete
Malathi RA201009 CE 2010 RA201009 5 CE501 CS501 DBMS
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

Data type supported by language


SRM
DATA STRUCTURES
INSTITUTE OF SCIENCE AND -TECHNOLOGY,
TYPES
CHENNAI.

Data Structures
Basic type

Primitive Data Non-Primitive


Structures Data Structures

Integer Real Character Boolean Linear Data Non-Linear Data


Structures Structures
Supported in Programming Languages
Arrays Trees
Linked List Graphs

Stack
Queue
ADT AND OPERATIONS
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ADT (ABSTRACT DATA TYPE)

Data declaration packaged with the operations that are meaningful for the data type.

• An ADT is a mathematical model of a data structure that specifies


the type of data stored, the operations supported on them, and
the types of parameters of the operations.
• An ADT specifies what each operation does, but not how it is done.
• ADT can be implemented using one of many different data
structures.
• First step in deciding what data structure to use in a program is to
specify an ADT for the program.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

STEPS TO BUILD ADT

• Understand the nature of information.


• Identify and determine operations to be included.
• Formally specify the property and communicate.
• Translate formal specification to align with identified language.
• Implement storage scheme and operational detail.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

OPERATIONS

Primitive Non primitive


• Create

• Create • Insert

• Select • Delete

• Update • Search

• Destroy • Traversing
• Sorting
• Merging
SPECIFICATIONS OF
ALGORITHMS, RECURSION AND
PERFORMANCE ANALYSIS
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ALGORITHM

• An algorithm is a sequence of unambiguous instructions for


solving a problem
• Different algorithms are possible for the same problem Different Idea , Speed
• Goal:
• Easy to understand and convert to program
• Use Resources efficiently Complexity Data Structure

Natural Language Definite

Pictorial Small
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

SPECIFICATION - CRITERIA

• Input: Zero or more data to be supplied


• Output: At least one data is produced
• Definiteness: Each instruction is clear and unambiguous
• Finiteness: All cases should terminate after finite number of
steps
• Effectiveness: Basic enough to be carried out
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

RECURSION

• A function that is defined in terms of itself


• Base case: Value of the function is known without resorting
recursion
• A particular instance of the function is not defined in terms of itself
• Recursive calls will keep on being made till base case is reached.
• Each case that need to be resolved recursively, the recursive
calls must always progress towards the base case.
• Recursion has hidden book keeping cost
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

RECURSION - RULES

• Base Case
• Making Progress
• Design Rule: Assume all recursive calls work
• Compound interest rule: Never duplicate work by solving the
same instance of a problem in separate recursive calls.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

PERFORMANCE ANALYSIS

• There are several ways to estimate the running time of the


program
• Ability to do analysis gives an insight into designing efficient
algorithms
• Help pinpoint bottle necks
• Time and Space utilization
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

PERFORMANCE ANALYSIS - RULES


for(a=0;a<m; a++)
{
for(i=0;i<n;i++) for(a=0;a<m; a++)
sum[a]=0;
sum=sum+arr[i];• For loop: Execution {
time of one iteration * no. of iterations
}
sum[a]=0;
for(i=0;i<n; i++)
for(i=0;i<n;i++) • Nested for: Running time j++)
for(j=0;j<n; of the statements * productfor(i=0;i<n;
of sizes i++)
for(j=0;j<n;j++) of all the loops for(j=0;j<n; j++)
sum[a]=sum[a]+arr[i][j];
sum=sum+arr[i][j]; sum[a]=sum[a]+arr[i][j];
• Consecutive statements: They add up }
if(condition) • If/else: never more than running time of test and larger of the
{
Set1 of statements;
running times of set1 or set2
} • Work inside out
else
{ • Analyze the function calls first
Set2 of statements;
}
SRM
WRONG USAGE
INSTITUTE OF RECURSION
OF SCIENCE AND TECHNOLOGY,
CHENNAI.

int factorial( int n) int fib( int n)


{ {
if(n<=1) if(n<=1) f1=0; f2=1; cnt=0 val=1;
return 1; return 1; while(cnt<n)
{
return (n*factorial(n-1)); return (fib(n-1)+fib(n-2));
printf(“%d\t”,f1);
} } f1=f2;
f2=val;
for(i=2;i<=n; i++) val=f1+f2;
{ cnt++;
factorial *= i; };

}
STYLE OF PROGRAMMING, REFINING
CODE AND COMPLEXITY

Space and Time


SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

STYLE OF PROGRAMMING

• Problem: Identify the kth element from a given set of n elements


• Style 1: Read n elements into an array and sort them in descending
order. Element in kth position is the solution Selection, Insertion, Bubble, Quick, Merge, Heap
• Style 2: Read first k elements and sort them in descending order. Read
every subsequent element and ignore if it is less than the kth element
else place it in its correct spot and eliminate the last element. The
element in kth position is the solution.
• Style 3: Build Maxheap of first k elements. For every subsequent
element if the element is less than root then add the element to the
heap, else ignore the element.The element in root is the solution.
• Style 4: Read n elements and use quick sort that terminates when the
pivot is the kth element.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

STYLE OF PROGRAMMING

• Writing a working code is not good enough


• If the data set is large – running time is important
• Program bottle necks
• Section to concentrate for optimizing
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

BEST PRACTICES

• int main( ) and return 0


• Logical variable names
• Proper escape sequence
• fgets() instead of gets()
• Functions should be used wherever appropriate
• Include Comments extensively
• Ensure that loops terminate finitely
• Use bit fields to save memory
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

CODING STANDARDS

• Compliance with Standards


• Consistency in Quality
• Security
• Reduced development cost
• Predict Undefined and unpredictable behaviours
REFINING CODE

SELF LEARNING
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

REFINING CODE

Code Optimization Pareto principle

Smaller size 90-10 Rule

Consume less memory

Execute Rapidly

Fewer I/O
SRM
CODEOFREFINEMENT
INSTITUTE SCIENCE AND TECHNOLOGY,
CHENNAI.

• Constant Folding:
• Compile time evaluation of constant expression
H/w performance improvement
• Scalars and Arrays that are constant need to be specified as const
• Conversion of explicit data flow Parameter passing instead of global declaration

• Conversion to fixed point


• Conversion of explicit memory access Avoid usage of pointers Access Pattern
• Constant Input enumeration
• Loop Rerolling Converse of unrolling
• Conversion of explicit control flow Eliminate function pointer
• Function Specialization
Frequent value for function parameter
• Algorithmic Specialization
• Pass by value return H/w specific algorithm
Array
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

COMPLEXITY

• M: Algorithm
• N: Size of Data Count of number of key operations
• Measures of efficiency: Time and Space
• Complexity : f(n) Memory needed by the algorithm

• Example Problem: Given a sentence you need to find the first


occurrence of a word Best Case Minimum value of f(n) 1
probability of number of comparisons p=1/n
1 1 1 1 #+1 Average Case Expected value of f(n) (n+1)/2
1× + 2× + 3× … + n× =
# # # # 2 Worst Case: Maximum value of f(n) n
MATHEMATICAL NOTATIONS AND
FUNCTIONS
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

FUNCTIONS AND NOTATIONS


Often used while programming

• Floor ! 7.45 = 7 −7.45 = −8


• Ceiling ! 7.45 = 8 −7.45 = −7
• Remainder k (mod M) = r k= Mq + r 0 ≤ r < M
75 mod 10 = 5 75= 10* 7 +5
• Mathematical Congruence a ≡ b (mod M)
0 ≡ M (mod M) a± M ≡ a (mod M)

• Integer INT(x) INT(7.45) = 7 INT(-7.45) = -7


• Absolute value ABS(x) |x|
Magnitude of the number ABS(7.45) = 7.45 ABS(-0.45) = 0.45 |-7| = 7
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

FUNCTIONS AND NOTATIONS


Often used while programming

• Sigma(∑) sum of series a1, a2, a3,…, an is represented as ∑%"#$ &"


• Factorial n! = 1x2x3x…x(n-1)x n 5! = 1x2x3x4x5 = 120
• Permutations Arrangement of elements n! permutation of n elements
$ ,⁄ .
• Exponents &' , &)' = ,,&
. = &' = .
& '
+
• Logarithms y = log 3 4 ≡ 6 7 = 4 log$< 100 = 2 &= 10> = 100

Common (10)
Natural (e ) ln x
Binary (2) log x
ASYMPTOTIC NOTATIONS – BIG O,
OMEGA AND THETA
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

BIG O NOTATION
Upper bound

• If f(n) is bounded by some multiple of g(n) for almost all n’s


• There exist n0 , M such that for all n>n0 ! " ≤ $( & " )
• Then f(n)= )(&("))
• Complexity of well known algorithms
• Linear Search: O(n)
• Binary Search: O(log n)
Non negative
• Bubble Sort: O(n2)
• Merge-Sort: O(n log n)
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

RATE OF GROWTH OF FUNCTIONS


SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

OMEGA NOTATION
Lower bound

• f(n) = !(g(n)) if there are constants c and n0 such that


f(n) ≥ cg(n) when n ≥ n0. " # ≥ %( ' # )

Several functions might be available

Example: f(n)=5n+1
f(n)= !(1)
f(n)= !(n)
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

THETA NOTATION
Lower and Upper bound

• f(n) = ! (g(n)) if and only if there c1, c2 and n0 such that

"1 $ % ≤ |( % | ≤ "2 $ %

for all n ≥ n0

( % =+ $ % and ( % =, $ %

-./0123: ( % = 18% + 9
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ASYMPTOTIC NOTATIONS
Describe the behaviour of a function f(n) when n is very large.

• f(n) = 21n2 + n and g(n) = n3

f(n)≤ g(n) n0=? f(n) = n2 + n and g(n) = n3


c=?
n > 1, n2 ≤ n 3 n ≤ = n3

n0=8 c=3 n2 + n ≤ 2n3 n0=?


c=?
f(n) = O(g(n)) n0=1, c=2

f(n) = O(g(n))
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ASYMPTOTIC NOTATIONS

• f(n) = n3 + 4n2 and g(n) = n2

If n≥ 0 then n3≤n3 + 4n2

If n≥ 1 then n2≤n3

n2≤n3 ≤n3 + 4n2 n0=?


c=?
f(n) = ! (g(n))
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ASYMPTOTIC NOTATIONS

• f(n)=an2 + bn + c
n0=?
c1=?
c2=?
c1=a/4
c2=7a/4

% (
n0= 2*max( , )
& &
DATA STRUCTURE : TYPES – LINEAR
AND NON LINEAR
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

LINEAR
Array (List)

Stack

Linked List

Queue
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
NON LINEAR
Tree
Graph

General Directed

Binary
Undirected
1D AND 2D ARRAY USING POINTERS –
INITIALIZE AND ACCESS
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

HUNGARIAN NOTATION

• Convention Indicates the type of the variable or the way it


should be
• Types – Prefix of the name indicate the nature of object
• System – actual data type
• variable used to store zero terminated string :
zsVariableName, Boolean variable will be represented as
bVariableName
• Apps – logical data type
• Unsafe variable – usVariableName
• Variable used for counting nVariableName
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
PREFIXES
• b for boolean • p for pointer
• ch for char • u32 for unsigned 32-bit integer
• w for word • fn for function
• dw for double word • arru8 array of unsigned 8-bit integers
• i for integer • rw Variable representing row position
• fp for floating-point • pX pointer to type of X
• db for double-precision floating • d difference between two values
point
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

POINTER ARRAYS

Syntax: data_type (*var_name)[size_of_array];


Example: int (*arr_ptr)[5], *a_ptr, arr[5][5] ={{10,20,30,23,12}, {15,25,35,33,88},
{45,25,77,57,54}, {65,34,67,33,99}, {44,45,55,44,65}};
1020 1024 1028 1032 1036
arr_ptr=&arr; arr_ptr 10 20 30 23 12
1040 1044 1048 1052 1056
a_ptr=&arr;
15 25 35 33 88
a_ptr
1060 1064 1068 1072 1076
45 25 77 57 54
1080 1084 1088 1092 1096
65 34 67 33 99
1100 1104 1108 1112 1116
44 45 55 44 65
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

POINTER ARRAYS

Syntax: data_type (*var_name)[size_of_array];


Example: int (*arr_ptr)[5], *a_ptr, arr[5][5] ={{10,20,30,23,12}, {15,25,35,33,88},
{45,25,77,57,54}, {65,34,67,33,99}, {44,45,55,44,65}};
1020 1024 1028 1032 1036
arr_ptr=&arr; arr_ptr 10 20 30 23 12
1040 1044 1048 1052 1056
a_ptr=&arr;
15 25 35 33 88
a_ptr
arr_ptr++; 1060 1064 1068 1072 1076
45 25 77 57 54
1080 1084 1088 1092 1096
65 34 67 33 99
1100 1104 1108 1112 1116
44 45 55 44 65
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

POINTER ARRAYS

Syntax: data_type (*var_name)[size_of_array];


Example: int (*arr_ptr)[5], *a_ptr, arr[5][5] ={{10,20,30,23,12}, {15,25,35,33,88},
{45,25,77,57,54}, {65,34,67,33,99}, {44,45,55,44,65}};
1020 1024 1028 1032 1036
arr_ptr=&arr; arr_ptr 10 20 30 23 12
1040 1044 1048 1052 1056
a_ptr=&arr;
15 25 35 33 88
a_ptr
arr_ptr++; 1060 1064 1068 1072 1076
45 25 77 57 54
a_ptr++;
1080 1084 1088 1092 1096
65 34 67 33 99
1100 1104 1108 1112 1116
44 45 55 44 65
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

POINTER ARRAYS

Syntax: data_type (*var_name)[size_of_array];


Example: int (*arr_ptr)[5], *a_ptr, arr[5][5] ={{10,20,30,23,12}, {15,25,35,33,88},
{45,25,77,57,54}, {65,34,67,33,99}, {44,45,55,44,65}};
1020 1024 1028 1032 1036
arr_ptr=&arr; arr_ptr 10 20 30 23 12
1040 1044 1048 1052 1056
a_ptr=&arr;
15 25 35 33 88
a_ptr
arr_ptr++; 1060 1064 1068 1072 1076
45 25 77 57 54
a_ptr++;
1080 1084 1088 1092 1096
65 34 67 33 99
1100 1104 1108 1112 1116
44 45 55 44 65
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

DYNAMIC MEMORY ALLOCATION

• malloc(): Allocate continuous block of memory


• Syntax: ptr = (castType*) malloc(size);
• Example: ptr = (float*) malloc(100 * sizeof(float));

• calloc(): Allocate continuous block of memory and


initialize to 0
• Syntax: ptr = (castType*)calloc(n, size);
• Example: ptr = (float*) calloc(25, sizeof(float));
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

DYNAMIC MEMORY ALLOCATION

• free(): To release previously allocated memory


• Syntax: free(ptr);

• realloc(): To enhance the size of the previously allocated


memory
• Syntax: ptr = realloc(ptr, x);
• Example: ptr = realloc(ptr, n2 * sizeof(int));
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

1D ARRAY USING POINTERS


//Using Pointer to an array
//Program to illustrate the usage of pointers and 1D Array
#include <stdio.h>
//Using Array name as pointer
int main()
#include <stdio.h>
{ int ii, ix[10], isum = 0,in;
int main() int *ixptr; int *ixptr;
{ int ii, ix[10], isum = 0,in;
ixptr=&ix;
printf("Enter number of values to be processed: %d”, &n);
printf("Enter number of values to be processed:”);
scanf("%d", &in);
scanf("%d", &in);
for(ii = 0; ii < in; ++ii)
for(ii = 0; ii < in; ++ii)
{ ixptr=(int*) malloc(in*sizeof(int)); {
scanf("%d", ix+ii); if (ixptr == NULL) scanf("%d", ixptr+ii);
// Accumulation of sum Equivalent
{ to scanf("%d", &ixptr[ii]);
isum += *(ix+ii); Printf(“No sufficient memory”); isum += *(ixptr+ii);
} Equivalent
Return 0; to isum += ixptr[ii]
}
printf("Sum = %d", isum); }
printf("Sum = %d", isum);
return 0;
return 0;
}
}
2D ARRAY AND DYNAMIC MEMORY
ALLOCATION

Write the program


STRUCTURES AND ARRAY OF
STRUCTURES
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

DECLARATION

• Syntax: • Example: Structure to hold student details


struct struct_Name struct Student
{ {
<data-type> member_name; int regNo;
<data-type> member_name; char name[25];
… int english, science, maths;
} list of variables; } stud;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

DECLARATION

• Syntax: struct Student


struct struct_Name {
{ int regNo;
<data-type> member_name; char name[25];
<data-type> member_name; int english, science, maths;
… };
}; struct Student stud;
struct struct_Name struct_var;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

INITIALIZATION

//Static Initialization of stud


stud.regNo=1425; strcpy(stud.name,“Banu”);
stud.English=78; stud.science=89; stud.maths=56;

//Dynamic Initialization of stud


scanf(“%d %s %d %d %d”,&stud.regNo, stud.name, &stud.English,&stud.science, &stud.maths);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ACCESSING AND UPDATING

struct Student
{
int regNo;
char name[25];
int english, science, maths;
};
struct Student stud;
scanf(“%d %s %d %d %d”,&stud.regNo, stud.name, &stud.english,&stud.science, &stud.maths);
printf("Register number = %d\n",stud.Regno); //Accessing member Regno
printf("Name %s",stud.name); //Accessing member name
stud.english= stud.english +10; //Updating member english
stud.science++; //Updating member science
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
NESTED STRUCTURE

struct Student struct Student


{ struct m
{
int regNo; {
int regNo;
char name[25]; int english;
char name[25];
struct marks int science;
struct m marks;
{ int english, science, maths; } int maths;
} Amar;
} Amar;
};
Amar.regNo; struct Student
Amar.marks.english; {
Amar.marks.science; int regNo;
Amar.marks.maths; char name[25];
struct {int english, science, maths } marks;
} Amar;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

ARRAY OF STRUCTURES

struct Student
{
int regNo;
char name[25];
int english, science, maths;
};
struct Student stud[10];
scanf(“%d%s%d%d%d”,&stud[1].regNo,stud[1].name,&stud[1].english,&stud[1].science,&stud[1].maths);
printf("Register number = %d\n",stud[1].Regno); //Accessing member Regno
printf("Name %s",stud[1].name); //Accessing member name
stud.[1]english= stud[0].english +10; //Updating member english
stud[1].science++; //Updating member science
ARRAY OF STRUCTURES SRM – DYNAMIC
INSTITUTEALLOCATION
OF SCIENCE AND TECHNOLOGY,
struct Student CHENNAI.
{
int regNo;
char name[25];
int english, science, maths;
};
struct Student *stud;
scanf(“%d”, &n);
for(i=0;i<n;i++)
scanf(“%d %s %d %d %d”,&stud[i]->regNo, stud[i]->name, &stud[i]->english, &stud[i]->science,
&stud[i]->maths);
printf(“Register number Name English Science Maths\n”);
for(i=0; i<n; i++)
{
printf("%d\t%s\t%d\t%d\t%d\n", stud[i]->regNo, stud[i]->name, &stud[i]->english, &stud[i]->science,
&stud[i]->maths);
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STRUCTURE WITH SELF REFERENCE
POINTER
struct node { stud2.regNo=100660;
int regNo; stud2.name=“Pushpi”;
char name[20]; stud2.link=NULL;
struct node* link; stud1.link=&stud2;
};
struct node stud1, stud2;
1000 102660 Nivi NULL
stud1.regNo=102660;
stud1.name=“Nivi”;
stud1.link=NULL; 7000 100660 Pushpi NULL
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STRUCTURE WITH SELF REFERENCE
POINTER
struct node { stud2.regNo=100660;
int regNo; stud2.name=“Pushpi”;
char name[20]; stud2.link=NULL;
struct node* link; stud1.link=&stud2;
};
struct node stud1, stud2;
1000 102660 Nivi 7000
stud1.regNo=102660;
stud1.name=“Nivi”;
stud1.link=NULL; 7000 100660 Pushpi NULL
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STRUCTURE WITH SELF REFERENCE
POINTER
struct node { stud2.regNo=100660;
int regNo; stud2.name=“Pushpi”;
char name[20]; stud2.link=NULL;
struct node* link; stud1.link=&stud2;
};
struct node stud1, stud2;
1000 102660 Nivi 7000
stud1.regNo=102660;
stud1.name=“Nivi”;
stud1.link=NULL; 7000 100660 Pushpi NULL
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.

USEFUL VIDEO LINKS

https://www.youtube.com/watch?v=Q_1M2JaijjQ

https://www.youtube.com/watch?v=dwApFR-MpLk

You might also like