0% found this document useful (0 votes)
47 views165 pages

DSA - Unit1 - Final - Updated

Uploaded by

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

DSA - Unit1 - Final - Updated

Uploaded by

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

21CSC201J

DATA STRUCTURES AND


ALGORITHMS
UNIT 1 - Introduction
Topics to be covered

Programming in C – Primitive data types, Structures, Self-


referential structures, Pointers and structures, Dynamic memory
allocation, Matrix multiplication; Data Structure – Definition,
Types, ADT, Operations; Mathematical notations - Big O, Omega
and Theta , Complexity – Time, Space, Trade off.
INTRODUCTION
BASIC TERMINOLOGY
Introduction
• Data Structure can be defined as the group of data elements
which provides an efficient way of storing and organizing data in
the computer so that it can be used efficiently.
• Some examples of Data Structures are arrays, Linked List,
Stack, Queue, etc.
• Data Structures are widely used in almost every aspect of
Computer Science i.e. Operating System, Compiler Design,
Artificial intelligence, Graphics and many more.
Basic Terminology
• Data are values or sets of values
• A data item refers to a single unit of values. Data items are
divided into subitems are called group items.
o For example, an employee’s name may be divided into three
subitems first name, middle name and last name but the
social security number would treated as a single name.
• Collections of data are organized into a hierarchy of fields,
records and files.
Basic Terminology (Cont..)
• Record can be defined as the collection of various data items.
o For example, if we talk about the student entity, then its name,
address, course and marks can be grouped together to form the
record for the student.
• Record is classified according to length. A file can have fixed
length records or variable length records.
• In fixed length records, all the records contain the same data
items with the same amount of space assigned to each data items.
• In variable length records, file records may contain different
lengths. Variable length records have a minimum and a maximum
length.
o For example, student records have variable length, since
different students take different numbers of courses
Basic Terminology (Cont..)
• A File is a collection of various records of one type of entity.
o For example, if there are 60 employees in the class, then
there will be 60 records in the related file where each record
contains the data about each employee.
• An entity represents the class of certain objects. It contains
various attributes. Each attribute represents the particular
property of that entity.
o For example, consider an employee of an organization:
Attributes: Name Age Sex Social Security
Number
Values: JOHN 34 M 134-24-5533
• Field is a single elementary unit of information representing the
attribute of an entity.
Basic Terminology – Example
• A professor keeps a class list containing the following data for
each student:
Name, Major, Student Number, Test Scores, Final Grades
a) State the entities, attributes and entity set of the list.
b) Describe the field values, records and file.
c) Which attribute can serve as primary keys for the list?
a) Each student is an entity, and the collection of students is the entity set.
The properties, name, major, and so on. of the students are the attributes.
b) The field values are the values assigned to the attributes, i. e., the actual
names, test scores, and so on. The field values for each student constitute a
record, and the collection of all the student records is the file.
c) Either Name or Student Number can serve as a primary key, since each
uniquely determines the student’s record. Normally the professor uses Name
as the primary key, but the registrar may use students Number.
Programming in C
Introduction
• C is a programming language developed at AT & T Bell
Laboratories of USA in 1972, designed and written by
“Dennis Ritchie”.
• C is highly portable i.e., software written for one
computer can be run on another computer.
• An important feature of C is its ability to extend itself.
• Basically it is a collection of functions.
History of C
• 1960: ALGOL (ALGOrithmic Language)
• 1967: BCPL (Basic Combined Programming
Language)
• 1970: B programming language (typeless)
• 1972: C: BCPL plus B with types
• 1978: Kernighan + Ritchie standard for C
• 1989: ANSI standard for C
Structure of C Program
Example
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Explanation

Elements Descriptions
/* Comments */ Comments are a way of explaining what makes a
program. Comments are ignored by the compiler
and used by others to understand the code.
#include<stdio. This is a preprocessor command that notify the
h> compiler to include the header file stdio.h in the
program before compiling the source-code.
int/void main() int/void is a return value.
main() The main() is the main function where program
execution begins. Every C program must contain
only one main function.
Braces Two curly brackets “{…}” are used to group all
printf() It is a function in C, which prints text on the
screen.
Data Types in C
Data Types in C
• Each variable in C has an associated data type.
• Each data type requires different amounts of memory
and has some specific operations which can be
performed over it.
Data Types in C
Primitive Data Types
• A primitive is a fundamental data type that
cannot be broken down into a more simple data
type
• They are
• character
• integer
• float
• void
Primitive Data Types - character
• It stores a single character
• requires a single byte of memory
• Format specifier - %c
• Keyword – char
• Example – char test = ‘h’;
Primitive Data Types - integer
• It stores whole numbers - zero, positive and
negative values
• It cannot store decimal values
• Usually requires 2 or 4 bytes of memory
• Format specifier - %d
• Keyword – int
• Example – int age=22;
Primitive Data Types – floating point
• It stores fractional numbers (real numbers)
• Usually requires 4 bytes of memory
• Format specifier - %f
• Keyword – float
• Example – float factor=22.442e2;
Primitive Data Types – void
• is an incomplete type. i.e. "nothing" or "no type".
• It is used in three kinds of situations
Type Description Example

Function returns A function with no return void exit (int status);


as void value has the return type
as void.
Function functions which do not int rand(void);
arguments as accept any parameter.
void
Pointers to void A pointer of type void * void *malloc( size_t size );
represents the address of
an object, but not its type returns a pointer to void
which can be casted to any
data type
Derived Data Types
• A derived type is formed by using one or more
basic types in combination.
• Using derived types, an infinite variety of
new types can be formed.
• They are
• arrays
• pointers
Derived Data Types – arrays
• An array is a collection of similar data types under a
single variable name in continuous memory location
• i.e. one or more than one integers can be stored under a
single name
• similarly for other data types too
• Example:
int new[5] = {1,2,3,4,5};
char name = “Program”;
Derived Data Types – pointers
• A pointer is a special variable that stores address of another
variable
• Declare a pointer before using it to store any variable address.
• Syntax:
type *ptr-variable-name; //declaration
variable-name = & ptr-variable-name; //assignment
• Example:
int *p;
1000 int num = 78;
p = &num;
User-defined Data Types (UDT)
• User-defined datatypes use the built-
in datatypes and other user-defined datatypes
• They are also called as data structures
• They are:
 Structure
 Union
 Enumeration
User-defined Data Types - Structure
• It is a package of variables of different types under a
single name.
• Structures are used to represent a record
• The struct statement defines a new data type, with
more than one member.
Example:
• Keyword – struct struct book {
• Syntax: int book-id = 234;
struct variable { char name[20] = “C – Program”;
} b1,b2;
member(s);
Printf (“%d”, b1.book-id”):
}; variable(s);
User-defined Data Types - Union
• A union is a special data type that allows to store
different data types in the same memory location.
• You can define a union with many members, but only
one member can contain a value at any given time.
• Unions provide an efficient way of using the same
memory location for multiple-purpose.
• The union tag is optional.
User-defined Data Types - Union
 Example:
• Keyword – union  Now, the union variable can
union number store an integer, a floating-point
• Syntax: { number,
characters.
or a string of

int roll;
union variable  It means a single variable, i.e.,
char option; same memory location, can be
{ float mark;
used to store multiple types of
data.
member(s); } n1,n2;

}; variable(s);
• The memory occupied by a union will be
large enough to hold the largest member of
the union
• In the above example, the memory allocated
is for float which is the largest data type
User defined Data Types - Enumeration
• Enumeration is a user defined datatype in C language.
• It is used to assign names to the integral constants
which makes a program easy to read and maintain.
• Keyword – enum
• Syntax:
enum variable {constant1, constant2,…}
• Example –
enum week{Sunday,Monday,Tuesday,Wednesday,…….};
enum week day;
Other Data types…..
Constants in C
• Constants refer to fixed values that the program may
not alter during its execution.
• These fixed values are also called literals.
• Constants can be of any of the basic data types like
an integer constant, a floating constant, a character
constant, or a string literal.
Constants in C
Introduction to Arrays
• An array is a collection of data that holds fixed number
of values of same type.
• Syntax:
data_type array_name[array_size];  Declaration
float mark[5];

• The size and type of arrays cannot be changed after its


declaration

34
Introduction to Arrays
• Initialization
int mark[5] = {19, 10, 8, 17, 9}; Initialization
int mark[] = {19, 10, 8, 17, 9};

35
Introduction to Arrays
• How to insert and print array elements?
int mark[5] = {19, 10, 8, 17, 9}
// insert different value to third element
mark[3] = 9;
// take input from the user and insert in third element
scanf("%d", &mark[2]);
// print first element of an array
printf("%d", mark[0]);

36
Introduction to Arrays
• Program to initialize an integer array with
five values and prints the array.
#include <stdio.h>
#include <conio.h> Output
int main()
{
Array elements are
int numbers[]={1,2,3,4,5}; 1
int i;
clrscr(); 2
printf("Array elements are\n");
3
for(i=0;i<=4;i++)
printf("%d\n",numbers[i]); 4
getch();
return 0;
5
}

37
Introduction to Arrays
#include <stdio.h>
int main()
{
Output
int marks[10], i, n, sum = 0, average;
Enter n: 5
printf("Enter n: ");
scanf("%d", &n);
Enter number1: 45
for(i=0; i<n; ++i) Enter number2: 35
{ Enter number3: 38
printf("Enter number%d: ",i+1); Enter number4: 31
scanf("%d", &marks[i]);
Enter number5: 49
sum += marks[i]; //sum=sum+marks[i]
Average = 39
}
average = sum/n;
printf("Average = %d", average);
return 0;
} 38
2 Dimensional Arrays
• Two-dimensional array are those type of array, which
has finite number of rows and finite number of
columns.
• The declaration form of 2-dimensional array is
Data_type Array_name [row size][column size];
• Example:
int a[3][3];

39
Example
#include<stdio.h> //Output
printf(“Given matrix:\n”);
#include<conio.h> Enter the order of matrix
for(i=0;i<r;i++)
int main() 2
{
{ 2
for(j=0;j<c;j++) Enter elements of 2*2 matrix
int matrix [3][3],i,j,r,c;
printf(“%d\t”,matrix[i][j]); 1
clrscr();
printf(“\n”); 2
printf(“Enter the order of matrix\n”);
3
scanf(“%d%d”,&r,&c); }
4
printf(“Enter elements of %d * %d return 0;
Given matrix :
matrix \n”,r,c);
} 1 2
for(i=0;i<r;i++)
3 4
for(j=0;j<c;j++)

scanf(“%d”,&matrix[i][j]);

40
2 Dimensional Arrays
• Example: Matrix Operations
• Addition
• Subtraction
• Scaling
• Determinant
• Transpose
• Multiplication

41
2 D Arrays – Example Program
Matrix Addition
#include <stdio.h> for(i=0;i<2;i++)
#include <conio.h> for(j=0;j<3;j++)
void main() c[i][j]=a[i][j]+b[i][j];
{
printf("\nTHE VALUES OF MATRIX C
int a[2][3],b[2][3],c[2][3],i,j;
ARE:\n");
clrscr();
printf("\nENTER VALUES FOR MATRIX A:\n");for(i=0;i<2;i++)
for(i=0;i<2;i++) {
for(j=0;j<3;j++) for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("%5d",c[i][j]);
printf("\nENTER VALUES FOR MATRIX B:\n");
for(i=0;i<2;i++) printf("\n");
for(j=0;j<3;j++) }
scanf("%d",&b[i][j]); getch();
}

42
2 D Arrays – Example Program
Transpose of a matrix in C
• To obtain Transpose of a matrix, we interchange rows and
columns of the matrix.

• For example, consider the following 3 X 2 matrix:


12
34
56
Transpose of the matrix:
135
246
43
2 D Arrays – Example Program
Transpose of a matrix in C
#include <stdio.h> printf("Transpose of the matrix:\n");
int main()
{ for (c = 0; c < n; c++) {
int m, n, c, d, matrix[10][10], transpose[10] for (d = 0; d < m; d++)
[10]; printf("%d\t", transpose[c][d]);
printf("Enter the number of rows and columns printf("\n");
of a matrix\n"); }
scanf("%d%d", &m, &n); return 0;
}
printf("Enter elements of the matrix\n");
for (c = 0; c < m; c++){
for (d = 0; d < n; d++){
scanf("%d", &matrix[c][d]);}}

for (c = 0; c < m; c++){


for (d = 0; d < n; d++){
transpose[d][c] = matrix[c][d];}}

44
2 D Arrays – Example Program
Determinant of a matrix in C
#include<stdio.h> determinant = a[0][0] * ((a[1][1]*a[2][2]) - (a[2]
int main(){
[1]*a[1][2])) -a[0][1] * (a[1][0]
int a[3][3], i, j; * a[2][2] - a[2][0] * a[1][2]) + a[0][2] * (a[1][0] * a[2]
[1] - a[2][0] * a[1][1]);
long determinant;
printf("Enter the 9 elements of matrix: ); printf("\nDeterminant of 3X3 matrix: %ld",
determinant);
for(i = 0 ;i < 3;i++)
for(j = 0;j < 3;j++)
return 0;
scanf("%d", &a[i][j]); }

printf("\nThe matrix is\n");


for(i = 0;i < 3; i++){
printf("\n");
for(j = 0;j < 3; j++)
printf("%d\t", a[i][j]);
}

45
2 D Arrays – Example Program
Scalar Matrix Multiplication
#include<stdio.h>
for(row = 0; rows< i; row++)
int main() for(col = 0; col < j; col++)
{ Multi[row][col] = Number *
Multi[row][col];
int i, j, row, col, Multi[10][10], Number;
printf("\n The Result of a Scalar Matrix
printf("\n Please Enter Number of rows and Multiplication is : \n");
columns\n");
for(row = 0; row < i; row++)
scanf("%d %d", &i, &j); for(col = 0; col < j; col++)
printf("\n Please Enter the Matrix Elements \ printf("%d \t ", Multi[row][col]);
n");
printf("\n");
for(row = 0; row < i; row++) return 0; }
for(col = 0;col < j; col++)
scanf("%d", Multi[rows][columns]);
printf("\n Please Enter the Multiplication value:
");
scanf("%d", &Number);

46
2 D Arrays – Example Program
Matrix Multiplication

47
2 D Arrays – Example Program
Matrix Multiplication
#include<stdio.h>
printf("multiply of the matrix=\n");
#include<stdlib.h>
for(i=0;i<r;i++) {
int main(){
for(j=0;j<c;j++) {
int a[10][10],b[10][10],mul[10]
[10],r,c,i,j,k; mul[i][j]=0;

printf("enter the number of row="); for(k=0;k<c;k++) {

scanf("%d",&r); mul[i][j]+=a[i][k]*b[k][j];

printf("enter the number of column="); }} }

scanf("%d",&c); //for printing result

printf("enter the first matrix element=\ for(i=0;i<r;i++) {


n"); for(j=0;j<c;j++) {
for(i=0;i<r;i++) { printf("%d\t",mul[i][j]);
for(j=0;j<c;j++) { }
scanf("%d",&a[i][j]); }}
printf("\n");
printf("enter the second matrix element=
}
\n"); for(i=0;i<r;i++) {
return 0;
for(j=0;j<c;j++) {
scanf("%d",&b[i][j]); } } }

48
POINTER
Definition and Features of Pointer

Definition:
• Pointer is a variable that stores the address of another variable.
Features
• Pointer saves the memory space.
• Execution time of pointer is faster because of direct access to
the memory location.
• With the help of pointers, the memory is accessed efficiently, i.e.,
memory is allocated and deallocated dynamically.
• Pointers are used with data structures.
Pointer declaration, initialization and accessing
• Consider the following statement
int q = 159;
In memory, the variable can be represented as follows −

q Variable

159 Value

1000 Address
Pointer declaration, initialization and
accessing(Cont..)
• Declaring a pointer
It means ‘p’ is a pointer variable which holds the address of
another integer variable, as mentioned in the statement below

int *p;
• Initialization of a pointer
Address operator (&) is used to initialise a pointer variable.
For example −
Variable Value Address
int q = 159;
int *p;
q 159 1000
p= &q; p 1000 2000
Pointer declaration, initialization and
accessing(Cont..)
• Accessing a variable through its pointer
To access the value of a variable, indirection operator (*) is used.

For example −
int q=159, *p,n;
p=&q;
n=*p
Here, ‘*’ can be treated as value at address.
p = &q;
n = *p; n =q
1D INITIALIZATION &
ACCESSING USING POINTERS
Pointers and one-dimensional arrays
The compiler allocates Continuous memory locations for all the
elements of the array.
The base address = first element address (index 0) of the array.
Syntax: data_type (var_name)[size_of_array]//Declaration
int *p;
• For Example − int a [5] = {10, 20,30,40,50};
int my_arr[] = {11, 22, 33, 44, 55};
Elements p = my_arr;

• The five elements are stored as follows −


Elements a[0] a[1] a[2] a[3] a[4]

Values 10 20 30 40 50
Address 1000 1004 1008 1012 1016

Base Address
a=&a[0]=1000
Pointers and one-dimensional arrays (Cont)
• If ‘p’ is declared as integer pointer, then, an array ‘a’ can be pointed by
the following assignment −
p = a; (or) p = &a[0];
• Every value of 'a' is accessed by using p++ to move from one element to
another element. When a pointer is incremented, its value is increased by
the size of the data type that it points to. This length is called the "scale
factor".
• The relationship between ‘p’ and 'a' is explained below
P = &a[0] = 1000
P+1 = &a[1] = 1004
P+2 = &a[2] = 1008
P+3 = &a[3] = 1012
P+4 = &a[4] = 1016
Pointers and one-dimensional arrays (Cont..)

• Address of an element is calculated using its index and the scale


factor of the data type. An example to explain this is given
herewith.
• Address of a[3] = base address + (3* scale factor of int)
= 1000 + (3*4)
= 1000 +12
= 1012
• Pointers can be used to access array elements instead of using
array indexing.
• *(p+3) gives the value of a[3].
• a[i] = *(p+i)
Example Program

• Following is the C program for pointers and one-dimensional arrays −


#include<stdio.h> main ( )
{
int a[5];
int *p,i;
printf ("Enter 5 lements");
for (i=0; i<5; i++)
scanf ("%d", &a[i]);
p = &a[0];
printf ("Elements of the array are");
for (i=0; i<5; i++)
printf("%d", *(p+i));
}
Output
When the above program is executed, it produces the following result −
Enter 5 elements : 10 20 30 40 50
Elements of the array are : 10 20 30 40 50
Example Program

P O I N T E R ARRAYS
Syntax: data_type (*var_name)[size_of_array]

•Exam ple:

int (*arr_ptr)[5], *a_ptr, arr[5][5] ={{10,20,30,23,12}, {15,25,35,33,88},


102 1024 1028 103 103
{45,25,77,57,54}, {65,34,67,33,99}, {44,45,55,44,65}};
0 20 30 2 6
arr_ptr= & arr; arr_ptr 10 23 12
104 1044 1048 105 105
a_ptr= & arr; 0 25 35 2 6
a_ptr 15 33 88
arr_ptr++; 106 1064 1068 107 107
a_ptr++; 0 25 77 2 6
45 57 54
108 1084 1088 109 109
0 34 67 2 6
65 33 99
110 1104 1108 111 111
Example Program : 1D array using Pointer
#include<stdio.h>
int main()
{
int array[5];
int i,sum=0;
int *ptr;
printf("\nEnter array elements (5 integer values):");
for(i=0;i<5;i++)
scanf("%d",&array[i]);
/* array is equal to base address * array = &array[0] */
ptr = array; for(i=0;i<5;i++)
{
//*ptr refers to the value at addresssum = sum + *ptr;
ptr++;
}
printf("\nThe sum is: %d",sum);
}
Output
Enter array elements (5 integer values): 1 2 3 4 5
The sum is: 15
2D INITIALIZATION &
ACCESSING USING
POINTERS
Pointers and two-dimensional arrays

• Memory allocation for a two-dimensional array is as follows −


0 1 2
int a[3] [3] = {1,2,3,4,5,6,7,8,9};
0 1 2 3
4 5 6
1
Base Address=1000=&a[0][0] 7 8 9
2
a[0][0] a[0][1] a[0][2]
Row 1-> 1 2 3
1000 1004 1008
a[1][0] a[1][1] a[1][2]
Row 2-> 4 5 6
1012 1016 1020

a[2][0] a[2][1] a[2][2]


Row 1-> 7 8 9
1024 1028 1032
Pointers and two-dimensional arrays

• Assigning Base Address to pointer


int *p
p=&a[0][0] (or)
p=a
Pointer is used to access the elements of 2-dimensional array as follows
a[i][j]=*(p+i*columnsize+j)
a[1] [2] = *(1000 + 1*3+2)
= *(1000 + 3+2)
= *(1000 + 5*4) // 4 is Scale factor
= * (1000+20)
= *(1020)
a[1] [2] = 6
Example Program

#include<stdio.h> main ( )
printf ("elements of 2d Output
{ int a[3] [3], i,j; array are");
int *p; When the above program is
for (i=0; i<3; i++) executed, it produces the
clrscr ( ); following result −
printf ("Enter elements of 2D
{
array"); for (j=0; j<3; j++) enter elements of 2D array 1 2
3456789
for (i=0; i<3; i++) {
{ Elements of 2D array are
printf ("%d \t", *(p+i*3+j));
for (j=0; j<3; j++) 123
{ 456
}
scanf ("%d", &a[i] [j]);
printf ("\n"); 789
}
} }
p = &a[0] [0]; getch ( );
}
Review Questions

1. Let’s consider 60 students took this course. Each student is


supposed to give a rating 1, 2, 3 4 or 5; one being bad and 5 being
good. Find the ratings are spread count the number of times each
rating was given.
2. Write a Program in C for the following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position(POS)
e. Exit.
Support the program with functions for each of the above
operations.
DECLARING
STRUCTURE AND
ACCESSING
Definition of Structures
• Structures are user defined data types
• It is a collection of heterogeneous data
• It can have integer, float, double or character data in it
• A structure is a collection of variables of different data
types grouped under a single name.
• struct<<structname>>
{
members;
}element;
We can access element.members;
Array Vs Structure
Declaration of Structures
Syntax: Example: Structure to hold
struct struct_N ame student details struct Student
{ {
<data-type> int regN o;
member_name; char
<data-type> name[25];
member_name; int english,
… science,
maths;
} list of variables;
} stud;
Example

70
Example

struct emp
{
int id;
char name[36];
int sal;
};
sizeof(struct emp) // --> 40 byte
(2byte+36byte+2byte)

71
Declaring a structure variable
struct <structure name>
{
Datatype1 member1;
Datatype2 member2;
Datatype3 member3;
...........
} variable1,variable2, …, variablen;
(OR)
struct <structure name>
{


};
struct <structure name> variable1,variable2, …, variablen;
Declaration of Structures
Syntax: struct Student
struct struct_N ame {
{ int regN o;
<data-type> char
member_name; name[25];
<data-type> int english,
member_name; science,
… maths;
}; };
struct struct_Name struct Student
struct_var; stud;
Initialization of Structures

// 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);
Accessing and Updating Structures
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\
// Accessing member
n",stud.Regno); printf("Name
Regno
%s",stud.name);
// Accessing member
stud.english= stud.english name
+10; stud.science++; // Updating member
english
// Updating member
Example Program
#include<stdio.h> void main()
#include<conio.h {
> struct emp e;
struct emp clrscr();
{ printf("Enter employee Id, Name, Salary: ");
int id; scanf("%d",&e.id); scanf("%s",&e.name);
scanf("%f",&e.sal);
char name[36]; printf("Id: %d",e.id); printf("\nName:
float sal; %s",e.name); printf("\nSalary: %f",e.sal);
}; getch();
}
Example Program
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali"); strcpy(
Book1.subject, "C Programming
Tutorial"); Book1.book_id = 6495407
Example Program
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing
Tutorial"); Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title); OUTPUT
printf( "Book 1 author : %s\n", Book1.author); Book 1 title : C Programming
printf( "Book 1 subject : %s\n", Book1.subject); Book 1 author : Nuha Ali
printf( "Book 1 book_id : %d\n", Book1.book_id); Book 1 subject : C Programming Tutorial
/* print Book2 info */ Book 1 book_id : 6495407
printf( "Book 2 title : %s\n", Book2.title); Book 2 title : Telecom Billing
printf( "Book 2 author : %s\n", Book2.author); Book 2 author : Zara Ali
printf( "Book 2 subject : %s\n", Book2.subject); Book 2 subject : Telecom Billing Tutorial
printf( "Book 2 book_id : %d\n", Book2.book_id); Book 2 book_id : 6495700
return 0;
}
Example Program
#include<stdio.h>
struct student Output
{ Enter the name, id, and marks of student 1
char name[20]; James
int id; 90
float marks; 90
}; Enter the name, id, and marks of student 2
void main() Adoms
{ 90
struct student s1,s2,s3; 90
printf("Enter the name, id, and marks of student 1 "); Enter the name, id, and marks of student 3
scanf("%s %d %f",s1.name,&s1.id,&s1.marks); Nick
printf("Enter the name, id, and marks of student 2 "); 90
scanf("%s %d %f",s2.name,&s2.id,&s2.marks); 90
printf("Enter the name, id, and marks of student 3 "); Printing the details....
scanf("%s %d %f",s3.name,&s3.id,&s3.marks); James 90 90.000000
printf("Printing the details....\n"); Adoms 90 90.000000
printf("%s %d %f\n",s1.name,s1.id,s1.marks); Nick 90 90.000000
printf("%s %d %f\n",s2.name,s2.id,s2.marks);
printf("%s %d %f\n",s3.name,s3.id,s3.marks);
}
DECLARING ARRAY OF
STRUCTURES AND
ACCESSING
Array of Structures
• Structure – for storing information of one particular
object
• Array of structure - used to store 100 such objects
• Example
struct Bookinfo
{
char bname[20];
int pages;
int price;
}Book[100];

81
Array of Structures
struct Student
{
int
regNo;
char
name[25
];
int
english,
science,
printf("Registermaths;
number = %d\ //Accessing member
};
n",stud[1].Regno); printf("Name Regno
struct Student stud[10]; stud.[1]english=
%s",stud[1].name); //Accessing member
scanf(“%d%s%d%d%d”,&stud[1].regNo,stud[1].name,&stud[1].english,&stud[1].science,
stud[0].english +10; stud[1].science++; name
&stud[1].maths); //Updating member
english
Example Program
OUTPUT
#include<stdio.h> int main()
Enter Records of 5 students
#include <string.h> {
Enter Rollno:1 Enter Name:Sonoo
struct student{ int i;
Enter Rollno:2 Enter Name:Ratan
int rollno; struct student st[5];
Enter Rollno:3 Enter Name:Vimal
char name[10]; printf("Enter Records of 5 students");
Enter Rollno:4 Enter Name:James
}; for(i=0;i<5;i++){
Enter Rollno:5 Enter Name:Sarfraz
printf("\nEnter Rollno:");
Student Information List:
scanf("%d",&st[i].rollno);
Rollno:1, Name:Sonoo
printf("\nEnter Name:");
Rollno:2, Name:Ratan
scanf("%s",&st[i].name);
Rollno:3, Name:Vimal
}
Rollno:4, Name:James
printf("\nStudent Information List:");
Rollno:5, Name:Sarfraz
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Array of Structures - Example
Program to store and display the // 2nd student's record
records of 3 students. record[1].id=2;
#include <stdio.h> strcpy(record[1].name, "Surendren");
#include <string.h> record[1].percentage = 90.5;
struct student // 3rd student's record
{ record[2].id=3;
int id;
strcpy(record[2].name, "Thiyagu");
char name[30];
record[2].percentage = 81.5;
float percentage;
}; for(i=0; i<3; i++)
int main() {
{ printf(" Records of STUDENT : %d \n",
int i; i+1);
struct student record[3]; printf(" Id is: %d \n", record[i].id);
// 1st student's record printf(" Name is: %s \n", record[i].name);
record[0].id=1; printf(" Percentage is: %f\n\
strcpy(record[0].name, "Raju"); n",record[i].percentage);
record[0].percentage = 86.5; } 84
Example: Program to store and display the
details of 50 students
int main()
#include <stdio.h>
{
#include <string.h> int i;
struct student struct student record[50];
{ printf(“Enter the record details\n”);
for(i=0;i<50;i++)
int id;
{
char name[30]; scanf( “%d%s%f”, &record[i].id, &record[i].name,
float percentage; &record[i].percentage);
}
};
#Display the details
for(i=0; i<50; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
85
Nested Structure
• When a structure contain another structure, it is called nested structure.
• Syntax
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 obj;
};

86
Nested Structures
struct Student struct Student struct m
{ { {
int regN o; int regN o; int
char char english;
name[25]; name[25]; int
struct struct m science;
} marks marks; int
Amar { } Amar; maths;
;struct Student };
{ int english, Amar.regNo;
science,
int regN o; Amar.marks.engli
maths;
char sh;
name[25]; Amar.marks.sci
}
struct {int ence;
english, Amar.marks.math
science, s;
Nested Structure - Example
void main()
#include<stdio.h> printf("\nDetails of Employees");
{
struct Address printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEnter Employee Salary : ");
{ { printf("\n\tEmployee Name : %s",E.Name);
int i; printf("\n\tEmployee Salary : %f",E.Salary);
char HouseNo[25];
struct Employee E; printf("\n\tEmployee House No :
char City[25]; printf("\n\tEnter Employee Id : "); %s",E.Add.HouseNo);
char PinCode[25]; scanf("%d",&E.Id); printf("\n\tEmployee City : %s",E.Add.City);
}; printf("\n\tEnter Employee Name : ");
printf("\n\tEmployee House No :
scanf("%s",&E.Name); %s",E.Add.PinCode);
struct Employee
printf("\n\tEnter Employee Salary : ");
{ scanf("%f",&E.Salary);
int Id; printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.HouseNo);
char Name[25];
printf("\n\tEnter Employee City : ");
float Salary; scanf("%s",&E.Add.City);
struct Address Add; printf("\n\tEnter Employee House No : ");
scanf("%s",&E.Add.PinCode);
};
88
Pointers and Structures
• Structures can be created and accessed using pointers.
int a;
int *p;
p=&a;
Pointers and Structures
• A pointer variable of a structure can be created as follows:
struct name
{
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
Accessing structure's member
through pointer
Referencing pointer to another address to access
memory
#include <stdio.h> int main()
typedef struct person {
{ struct person *personPtr, person1;
int age; personPtr = &person1; // Referencing pointer to
float weight; memory address of person1
}; printf("Enter integer: ");
scanf("%d",&(*personPtr).age);
printf("Enter number: ");
scanf("%f",&(*personPtr).weight);
printf("Displaying: ");
printf("%d%f",(*personPtr).age,
(*personPtr).weight);
return 0;
}
Accessing structure's member through
pointer using dynamic memory allocation
#include <stdio.h> // Above statement allocates the memory
#include <stdlib.h> for n structures with pointer personPtr
pointing to base address */
struct person {
for(i = 0; i < num; ++i)
int age; {
float weight; printf("Enter name, age and weight of
char name[30]; the person respectively:\n");
}; scanf("%s%d%f", &(ptr+i)->name,
int main() &(ptr+i)->age,
&(ptr+i)->weight);
{
}
struct person *ptr;
printf("Displaying Information:\n");
int i, num;
for(i = 0; i < num; ++i)
printf("Enter number of persons: printf("%s\t%d\t%.2f\n", (ptr+i)-
"); >name, (ptr+i)->age, (ptr+i)-
scanf("%d", &num); >weight);
ptr = (struct person*) malloc(num return 0;
* sizeof(struct person)); }
Self-referential structures
• A structure which contains a pointer to itself is
known as self referential structures.
struct name
{
member 1;
member 2;
...
struct name *pointer;
};
Self-referential structures
• Example for Self referential structure is – Linked List
• Linked List is a collection of nodes which are not
necessary to be in adjacent memory location.
• Each node – 2 fields (data field, address field)
Self-referential structures
• Singly Linked List
• Circular Linked List
• Doubly Linked List
• Circular double linked list
Program implement Self-referential structures

#include<stdio.h> printf(“Enter the Ist node data); thirdaddr=NULL;


scanf(‘%d”, &firstdata); temp=first;
main()
firstaddr = second;
{ while(temp!= NULL)
printf(“Enter the 2nd node
struct node data); {
{ scanf(‘%d”, &seconddata); printf(“%d”,
int data; firstaddr = third; tempdata);
printf(“Enter the 3rd node
struct node *addr; temp = tempaddr;
data);
}*first,*second, *third; scanf(‘%d”, &thirddata);
}
secondaddr = second; }
Dynamic memory allocation
• Dynamic memory allocation allows your program to obtain more memory space
while running, or to release it if it's not required.
• library functions under "stdlib.h" for dynamic memory allocation
Dynamic Memory Allocation
• malloc()
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory of
specified size and return a pointer of type void which can
be casted into pointer of any form.
• Syntax of malloc()
• ptr = (cast-type*) malloc(byte-size)
ptr = (int*) malloc(100 * sizeof(int));
Dynamic Memory Allocation
• calloc()
• The name calloc stands for "contiguous
allocation".
• The only difference between malloc() and calloc()
is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of
memory.
• Syntax of calloc()
• ptr = (cast-type*)calloc(n, element-size);
• This statement will allocate contiguous space in
memory for an array of n elements.
• example:
Dynamic Memory Allocation
• free()
• Dynamically allocated memory created with either calloc()
or malloc() doesn't get
• freed on its own. You must explicitly use free() to release
the space.
• syntax of free()
• free(ptr);
Dynamic Memory Allocation
Sum of Element in an array printf("Enter elements of array:
");
#include <stdio.h>
for(i = 0; i < num; ++i)
#include <stdlib.h> Output:
{ Enter the elements in the
int main()
scanf("%d", ptr + i); array:4
{ Enter elements of array:7
} 20
int num, i, *ptr, sum = 0;
3
printf("Enter number of elements 5
in the Array: "); for(i = 0; i < num; ++i) Sum of Elements in the
scanf("%d", &num); { given array:35
ptr = (int*) malloc(num * sum += *(ptr + i);
sizeof(int));
}
if(ptr == NULL)
printf("Sum of Elements in the
{ given array is : %d", sum);
printf("Error! Unable to allocate free(ptr);
memory.");
return 0;
exit(0);
}
}
Review Questions
1. Write a C program for student mark sheet using structure
2. Write a C program using structure to find students grades in a
class
3. Write a C program for book details using structure
4. Calculating the area of a rectangle using structures in C
language.
DATA STUCTURES
Data Structures
• Data Structure can be defined as the group of data elements
which provides an efficient way of storing and organizing
data in the computer so that it can be used efficiently.
• Data Structures are the main part of many computer science
algorithms as they enable the programmers to handle the data
in an efficient way.
• It plays a vital role in enhancing the performance of a software
or a program as the main function of the software is to store and
retrieve the user's data as fast as possible.
Classification of Data Structures
Primitive & Non-Primitive of Data Structures
• Primitive data structures are the fundamental data types
which are supported by a programming language.
• Some basic data types are integer, real(float), character, and
Boolean.
• Non-primitive data structures are data structures which are
created using primitive data structures.
• Examples of such data structures include linked lists, stacks,
trees, and graphs.
• Non-primitive data structures can further be classified into two
categories: linear and non-linear data structures.
Linear Data Structures
• If the elements of a data structure are stored in a linear or
sequential order, then it is a linear data structure.
• Examples include arrays, linked lists, stacks, and queues.
• Linear data structures can be represented in memory in two
different ways.
• One way is to have a linear relationship between elements by
means of sequential memory locations.
• The other way is to have a linear relationship between elements
by means of links.
Non Linear Data Structures
• If the elements of a data structure are not stored in a
sequential order, then it is a non-linear data structure.
• The relationship of adjacency is not maintained between
elements of a non-linear data structure.
• Examples include trees and graphs.
Review Questions
• A hospital maintains a patient file in which each record contains the
following data:
Name, Admission date, Social security number, Room, Bed number,
Doctor
a) Which items can serve as primary keys?
b) Which pair of items can serve as a primary key?
c) Which items can be group items?
• Which of the following data items may lead to variable length records when
included as items in the record:
(a) age, (b) sex, (c) name of spouse, (d) names of children, (e) education,
(f) previous employers
DATA STUCTURE
OPERATIONS
Data Structure Operations

• The data in the data structures are processed by certain


operations.
o Traversing
o Searching
o Inserting
o Updating
o Deleting
o Sorting
o Merging
Data Structure Operations (Cont..)
• Traversing - Visiting each record so that items in the records
can be accessed.
• Searching - Finding the location of the record with a given key
or value or finding all records which satisfy given conditions.
• Inserting - Adding a new record to the data structure.
• Updating – Change the content of some elements of the record.
• Deleting - Removing records from the data structure.
• Sorting - Arranging records in some logical or numerical order.
o (Eg: Alphabetic order)
• Merging - Combing records from two different sorted files into
a single file.
Example
• An organization contains a membership file in which each record
contains the following data for a given member:
Name, Address, Telephone Number, Age, Sex
a. Suppose the organization wants to announce a meeting
through a mailing. Then one would traverse the file to obtain
Name and Address of each member.
b. Suppose one wants to find the names of all members living in a
particular area. Again traverse and search the file to obtain
the data.
c. Suppose one wants to obtain Address of a specific Person. Then
one would search the file for the record containing Name.
d. Suppose a member dies. Then one would delete his or her
record from the file.
Example
e. Suppose a new person joins the organization. Then one
would insert a record into the file
f. Suppose a member has shifted to a new residence his/her
address and telephone number need to be changed. Given
the name of the member, one would first need to search for
the record in the file. Then perform the update operation,
i.e. change some items in the record with the new data.
g. Suppose one wants to find the number of members whose
age is 65 or above. Again one would traverse the file,
counting such members.
DATA STRUCTURES
AND ITS TYPES
Data Structure
• A data structure is basically a group of data elements that are
put together under one name
• Defines a particular way of storing and organizing data in a
computer so that it can be used efficiently
• Data Structures are used in
 Compiler design
 Operating system
 Statistical analysis package
 DBMS
• The selection of an appropriate data structure provides the most
efficient solution
Types in Data Structure
Types of Data Structure
Primitive Data Structures:
Primitive data structures are the fundamental data types which are supported by a
programming language. Some basic data types are
 Integer
 Real
 Character
 Boolean

Non-Primitive Data Structures:


Non-primitive data structures are those data structures which are created using
primitive data structures. Examples of such data structures include
 linked lists
 stacks
 trees
 graphs
LINEAR AND NON-
LINEAR DATA
STRUCTURES
Types of Data Structure – Non
Primitive
Linear
Arrays Linked List
• An array is a collection of • Dynamic data structure in
similar type of data items and which elements (called nodes)
each data item is called an form a sequential list
element of the array.
Types of Data Structure – Non Primitive
Linear
Stack Queue
• Linear data structure in which • Linear data structure in which
insertion and deletion of the element that is inserted
elements are done at only one first is the first one to be
end, which is known as the taken out
top of the stack
Types of Data Structure – Non Primitive - Non
Linear

• The data structure where data items are not organized


sequentially is called non linear data structure
• Types
• Trees
• Graphs
Types of Data Structure – Non Primitive - Non
Linear

TREES
• A tree is a non-linear data structure which consists of a
collection of nodes arranged in a hierarchical order.
• One of the nodes is designated as the root node, and the
remaining nodes can be partitioned into disjoint sets such that
each set is a sub-tree of the root.
Types of Data Structure – Non Primitive - Non
Linear
GRAPHS
• A graph is a non-linear data structure which is a collection of
vertices (also called nodes) and edges that connect these
vertices.
• A graph is often viewed as a generalization of the tree structure.
• every node in the graph can be connected with another node in
the graph.
• When two nodes are connected via an edge, the two nodes are
known as neighbours.
Review Questions
1. Compare a linked list with an array.
2. Is Array static structure or dynamic structure (TRUE / FALSE)
3. The data structure used in hierarchical data model is _________
4. In a stack, insertion is done at __________
5. Which Data Structure follows the LIFO fashion of working?
6. The position in a queue from which an element is deleted is
called as __________
ABSTRACT DATA TYPE
Abstract Data Types
• An Abstract Data type (ADT) is a type for objects whose behavior is
defined by a set of value and a set of operations.
• ADT refers to a set of data values and associated operations that are
specified accurately, independent of any particular implementation.
• The ADT consists of a set of definitions that allow us to use the
functions while hiding the implementation.
• Abstract in the context of data structures means everything except
the detailed specifications or implementation.
• Data type of a variable is the set of values that the variable can take.

ADT = Type + Function Names + Behaviour of


each function
• Examples: Stacks, Queues, Linked List
ADT Operations
• While modeling the problems the necessary details are
separated out from the unnecessary details. This process of
modeling the problem is called abstraction.
• The model defines an abstract view to the problem. It focuses
only on problem related stuff and that you try to define
properties of the problem.
• These properties include
o The data which are affected.
o The operations which are identified.
ADT Operations ( Cont..)
• Abstract data type operations are
o Create - Create the data structure.
o Display - Displaying all the elements stored in the data
structure.
o Insert - Elements can be inserted at any desired position.
o Delete - Desired element can be deleted from the data
structure.
o Modify - Any desired element can be deleted/modified from
the data structure.
Abstract Data Types Model
• The ADT model has two different parts
functions (public and private) and
data structures.
• Both are contained within the ADT
model itself, and do not come within
the scope of the application program.
• Data structures are available to all of
the ADT’s functions as required, and a
function may call any other
function to accomplish its task.
• Data structures and functions are
within the scope of each other.
Abstract Data Types Model (Cont..)
• Data are entered, accessed, modified
and deleted through the external
application programming interface.
• For each ADT operation, there is an
algorithm that performs its specific
task.
• The operation name and parameters
are available to the application, and
they provide only an interface to the
application.
• When a list is controlled entirely by
the program, it is implemented using
simple structure.
Review Questions

• ______ are used to manipulate the data contained in various data


structures.
• In ______, the elements of a data structure are stored
sequentially.
• ______ of a variable specifies the set of values that the variable
can take.
• Abstract means ______.
• If the elements of a data structure are stored sequentially, then
it is a ______.
MATHEMATICAL
NOTATIONS
Exponents and Logarithms
• The concept of logarithms is related
• Exponent means how
to exponents.
many times a number is • If b is a positive number, then the
logarithm of any positive number x to
multiplied by itself. If m
the base b is written as logbx.
is a positive integer, then: • It represents the exponent to which b
• am = a * a * a * …. * a (m should be raised to get x i.e. y = logbx
and by = x
times) and a-m = 1 / am E.g.
log28 = 3 , Since 23 = 8
• E.g.
log10.001 = -3 = 0.001, since 10-3
• 24 = 2 * 2 * 2 * 2 = 16
logb1 = 0 , since b0 =1
• 2-4 = 1 / 24 = 1/16 logbb = 1, since b1 = b
Mathematical Functions
Mathematical Functions (Cont..)
ASYMPTOTIC
NOTATIONS
BIG O, OMEGA
Asymptotic Analysis
• The time required by an algorithm falls under three types −
• Best Case − Minimum time required for program execution.
• Average Case − Average time required for program
execution.
• Worst Case − Maximum time required for program
execution.

138
Asymptotic Analysis (Cont..)
• Asymptotic analysis of an algorithm refers to defining the
mathematical foundation/framing of its run-time performance.
• Derive the best case, average case, and worst case scenario of
an algorithm.
• Asymptotic analysis is input bound.
• Specify the behaviour of the algorithm when the input size
increases
• Theory of approximation.
• Asymptote of a curve is a line that closely approximates a curve
but does not touch the curve at any point of time.

139
Asymptotic notations
• Asymptotic notations are mathematical tools to represent the
time complexity of algorithms for asymptotic analysis.
• Asymptotic order is concerned with how the running time of
an algorithm increases with the size of the input, if input
increases from small value to large values

1. Big-Oh notation (O)


2. Big-Omega notation (Ω)
3. Theta notation (θ)
4. Little-oh notation (o)
5. Little-omega notation (ω)

06/11/2024 140
Big-Oh Notation (O)
• Big-oh notation is used to define the worst-case running time of an
algorithm and concerned with large values of n.

• Definition: A function t(n) is said to be in O(g(n)), denoted as t(n)


ϵ O(g(n)), if t(n) is bounded above by some constant multiple of
g(n) for all large n. i.e., if there exist some positive constant c and
some non-negative integer n0 such that

t(n) ≤ cg(n) for all n ≥ n0

• O(g(n)): Class of functions t(n) that grow no faster than g(n).


• Big-oh puts asymptotic upper bound on a function.

06/11/2024 141
Big-Oh Notation (O)

06/11/2024 142
Big-Omega notation (Ω)
• This notation is used to describe the best case running time of
algorithms and concerned with large values of n.

• Definition: A function t(n) is said to be in Ω(g(n)), denoted as t(n)


ϵ Ω(g(n)), if t(n) is bounded below by some positive constant
multiple of g(n) for all large n. i.e., there exist some positive
constant c and some non-negative integer n0. Such that

t(n) ≥cg(n) for all n ≥ n0

• It represents the lower bound of the resources required to solve a


problem.

06/11/2024 143
Big-Omega notation (Ω)

06/11/2024 144
Big– THETA Θ Notation
Big– THETA Θ Notation
Example - THETA
• Show that n2 /2 – 2n = Θ(n2 ).
Example - THETA
Review Questions
• Indicate constant time complexity in terms of Big-O notation.
A. O(n)
B. O(1)
C. O(logn)
D. O(n^2)
• Big oh notation is used to describe __________
• Big O Notation is a _________function used in computer science
to describe an ____________
• Big Omega notation (Ω) provides _________bound.
• Given T1(n) =O(f(n)) and T2(n)=O(g(n).Find T1(n).T2(n)

149
Review Questions
1. Which function gives the positive value of the given input?
2. K (mod) M gives the reminder of ____ divided by ____
3. For a given set of number n, the number of possible
permutation will be equal to the ____________ value of n.
4. ________Notation is used to specify both the lower bound and
upper bound of the function.
COMPLEXITY – TIME ,
SPACE TRADE OFF
SPACE COMPLEXITY
• Space complexity is the total amount of memory space used
by an algorithm/program including the space of input
values for execution. So to find space-complexity, it is enough
to calculate the space occupied by the variables used in an
algorithm/program.
• Space complexity S(P) of any algorithm P is,
• S(P) = C + SP(I)
•Where C is the fi xed p a r t and S(I) is the variable p a r t
of the algorithm which depends on instance
Example:
characteristic I. Here we have three variables A, B & C and
 Algorithm: SUM(A, B) one constant. Hence S(P) = 1+3.
 Step 1 - START Space requirement depends on data types of
 Step 2 - C ← A + B + 10 given variables & constants. The number will be
multiplied accordingly.
 Step 3 – Stop
How to calculate Space Complexity of an Algorithm?

• In the Example program, 3 integer variables are used.


• The size of the integer data type is 2 or 4 bytes which depends on the
architecture of the system (compiler). Let us assume the size as 4 bytes.
• The total space required to store the data used in the example program is 4
+4+4 = 12, Since no additional variables are used, no extra space is
required. Hence, space complexity for the example program is O(1), or
constant.
EXAMPLE 2

• In the code given above, the array stores a maximum of n integer elements. Hence,
the space occupied by the array is 4 * n. Also we have integer variables such as n, i
and sum.
• Assuming 4 bytes for each variable, the total space occupied by the program is 4n +
12 bytes.
• Since the highest order of n in the equation 4n + 12 is n, so the space complexity
is O(n) or linear.
EXAMPLE 3

#include<stdio.h>
int main()
{
int a = 5, b = 5, c;
c = a + b;
printf("%d", c);
}
Time Complexity
• Time Complexity of an algorithm r e p r e s e n t s the
amount of time required by the algorithm to r u n to
completion.
• Time r e q u i r em en ts can be defi ned as a numerical
function T(n), where T(n) can be m eas u r ed as the
number of steps, provided each step consumes
constant time.
• Eg. Addition of two n-bit integers takes n steps.
• Total computational time is T(n) = c*n,
• w h er e c is the time taken for addition of two bits.
• Here, we observe that T(n) grows linearly as input
size increases.
Time Complexity (Cont..)
Two methods to find the time complexity for an algorithm
1. Count variable method

2. Table method

06/11/2024 157
Count Variable Method

158
Table Method
• The table contains s/e and frequency.

• The s/e of a statement is the amount by which the count


changes as a result of the execution of that statement.

• Frequency is defined as the total number of times each


statement is executed.

• Combining these two, the step count for the entire


algorithm is obtained.

06/11/2024 159
Example 1

06/11/2024 160
Example 3
Consider the following piece of code...

int sum(int a, int b)


{
return a+b;
}
In the above sample code, it requires 1 unit of time to calculate a+b and 1 unit of time to return the
value. That means, totally it takes 2 units of time to complete its execution. And it does not change
based on the input values of a and b. That means for all input values, it requires the same amount of
time i.e. 2 units.
If any program requires a fixed amount of time for all input values then its time complexity is
said to be Constant Time Complexity
Example 4

Cost Time
s
i = 1; c1 1
sum = 0; c2 1
while (i <= n) { c3 n+1
i = i + 1; c4 n
sum = su m + i; c5 n
}

3n+3
Total Cost =c1 + c2 + (n+1)*c3 + n*c4 + n*c5
The time required for this algorithm is proportional to n
Example 5

Total Cost= c1 + c2 + (n+1)*c3 + n*c4 +


n*(n+1)*c5+n*n*c6+n*n*c7+n*c8
The time required for this algorithm is proportional
to n2
Review questions
1. Calculate the time complexity for the below algorithms using
table method

164
2.

3.

06/11/2024 165

You might also like