DSA - Unit1 - Final - Updated
DSA - Unit1 - Final - Updated
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
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];
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.
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]); }
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;
scanf("%d",&r); mul[i][j]+=a[i][k]*b[k][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;
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..)
P O I N T E R ARRAYS
Syntax: data_type (*var_name)[size_of_array]
•Exam ple:
#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
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
/* 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
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.
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
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.
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.
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 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.
06/11/2024 159
Example 1
06/11/2024 160
Example 3
Consider the following piece of code...
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
164
2.
3.
06/11/2024 165