0% found this document useful (0 votes)
14 views61 pages

Unit-1 (Part-1)

The document provides an overview of C programming, including its structure, compilation process, and memory management. It discusses various data structures, their classifications, and differences between linear and non-linear data structures. Additionally, it highlights the importance of data structures in programming efficiency and includes examples such as arrays, linked lists, stacks, queues, trees, and graphs.
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)
14 views61 pages

Unit-1 (Part-1)

The document provides an overview of C programming, including its structure, compilation process, and memory management. It discusses various data structures, their classifications, and differences between linear and non-linear data structures. Additionally, it highlights the importance of data structures in programming efficiency and includes examples such as arrays, linked lists, stacks, queues, trees, and graphs.
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/ 61

Unit-1

Introduction
Books
1. S. Lipschutz, "Data Structures with C", Schaum's
Outline Series, McGraw-Hill Education (India) Pvt. Limited,
2017.
2. Y. P. Kanetkar, "Data structures through C", 4rd
Edition, New Delhi: BPB, 2022.
Sample Code of C “Hello World” Program
Structure of a C program
• Documentations (Documentation Section): The Documentation section usually contains the collection
of comment lines giving the name of the program, author’s or programmer’s name and few other
details.
• Preprocessor Statements (Link Section): It links predefined functions in library files into your program
• Global Declarations : used to define those variables that are used globally within the entire program and
is used in more than one function
• The main() function
– Local Declarations
– Program Statements & Expressions
• User Defined Functions
#include < stdio.h >
#define PI 3.141
int main()
{
float radius, area;
printf("Enter radius of circle\n");
scanf("%f", & radius);
area = PI * radius * radius;
printf("Area of circle : %0.4f\n", area);
return 0;
}
Compiling and executing a ‘C’ code
#include <stdio.h>
#define SOMETHING "Hello World" Preprocessor directive
int main()
{
/* Using a macro to print 'Hello World'*/
printf(“Hi”);
printf(SOMETHING);
return 0;
}

https://www.geeksforgeeks.org/stringizing-and-token-pasting-o
perators-in-c
/
Compiling and executing a ‘C’ code

• There are four main stages through which a source code passes in order to finally become an executable.

The four stages for a C program to become an executable are the following:
• Pre-processing
• Compilation
• Assembly
• Linking
Compiling and executing a ‘C’ code
1) Preprocessing: This is the very first stage through which a source code passes. In this stage the following tasks are
done:
• Removal of Comments
• Expansion of Macros
• Expansion of the included files.

gcc -E -o Program1.i Program1.c

Analysis:
• printf contains now “Hello World” rather than the macro SOMETHING that’s because macros have expanded.
• Comments are stripped off.
• #include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included in our
source file.
Compiling and executing a ‘C’ code
2) Compilation:In this phase compilation proper takes place. The compiler (ccl)
translates Program1.i into Program1.s. File Program1.s contains assembly code. You can explicitly tell gcc to
translate Program1.i to Program1.s by executing the following command.
gcc -S Program1.i
• The command line option -S tells the compiler to convert the preprocessed code to assembly language
without creating an object file. After having created Program1.s we can see the content of this file. While
looking at assembly code we may note that the assembly code contains a call to the external
function printf.
3) Assembly: Here, the assembler (as) translates Program1.s into machine language instructions, and
generates an object file Program1.o. You can invoke the assembler at your own by executing the following
command.
gcc Program1.s -o Program1.o
Compiling and executing a ‘C’ code
• The above command will generate Program1.o as it is specified with -o option. And, the resulting file
contains the machine instructions for the classic "Hello World!" program, with an undefined reference
to printf.
4) Linking: This is the final stage in compilation of "Hello World!" program. This phase links object files to
produce final executable file. An executable file requires many external resources (system functions, C run-
time libraries etc.). Regarding our "Hello World!" program you have noticed that it calls the printf function
to print the 'Hello World!' message on console. This function is contained in a separate pre compiled object
file printf.o, which must somehow be merged with our Program1.o file. The linker (ld) performs this task for
you. Eventually, the resulting file helloworld is produced, which is an executable. This is now ready to be
loaded into memory and executed by the system.
GCC Compilation
Process
Structure of a C program
* Comments */ This is a comment block, which is ignored by the compiler.
Comment is used anywhere in program to add info about
program or code block, which can be helpful for programmer to
understand the code easily in feature.
#include<stdio.h> This is a preprocessor command to include the header file stdio.h
in the program before compiling the source-code.
main() The main() is the main function where program execution
begins. Every C program must contain only one main function.

Braces The Curly braces which shows how much the main() function has
its scope.
printf() It is a predefined (already written and compiled) function in C,
which prints text on the screen
return 0 At the end of the main function returns value 0.
Video Links
• https://www.youtube.com/watch?v=BgcygHaX7sA

• https://www.youtube.com/watch?v=4P7-gMJWFZA

• https://www.youtube.com/watch?v=Unwu7tkJT5U&t=2s
Assembler, Compiler, Interpreter, Loader & Linker
• https://www.efaculty.in/c-language/concept-of-assembler-compiler-interpreter-loader-and-linker/#:~:tex
t=The%20C%20compiler%2C%20compiles%20the,execution%20(executable%20machine%20code)
.

• https://www.geeksforgeeks.org/python-compiled-or-interpreted/
Memory Management in C
Memory Management in C
A typical memory layout of a running process
1. Text Segment: which contains executable instructions. the text segment is often read-
only, to prevent a program from accidentally modifying its instructions.
2. Initialized Data Segment: contains the global variables and static variables that are
initialized by the programmer.
• Data segment is not read-only, since the values of the variables can be altered at run
time.
• This segment can be further classified into initialized read-only area and initialized
read-write area.
• Example: A global C statement int a=1 would be stored in initialized read-write area.
And a global C statement like const char* a = “hello world” makes the string literal
“hello world” to be stored in initialized read-only area and the character pointer
variable string in initialized read-write area.
Memory Management in C
3. Uninitialized Data Segment: Uninitialized data segment, often called the “bss” segment, named after an
ancient assembler operator that stood for “block started by symbol.
• Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing.
4. Stack: The stack area traditionally adjoined the heap area and grew the opposite direction; when the
stack pointer met the heap pointer, free memory was exhausted.
• The stack grows and shrinks as functions push and pop local variables
• There is no need to manage the memory yourself, variables are allocated and freed automatically
• The stack has size limits
• Stack variables only exist while the function that created them, is running
Memory Management in C
• Variables created on the stack will go out of scope and are automatically deallocated.
• Much faster to allocate in comparison to variables on the heap.
• Implemented with an actual stack data structure.
• Stores local data, return addresses, used for parameter passing.
• Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep
recursion, very large allocations).
• Data created on the stack can be used without pointers.
4. Heap: It is used on demand to allocate a block of data for use by the program.
• Slower to allocate in comparison to variables on the stack.
• Can have fragmentation when there are a lot of allocations and deallocations.
Memory Management in C
• In C++ or C, data created on the heap will be pointed to by pointers and allocated
with new or malloc respectively.
• We use the heap if we don't know exactly how much data we will need at run time.

• https://www.geeksforgeeks.org/memory-layout-of-c-program/

Static variable in C
• https://www.geeksforgeeks.org/static-variables-in-c/
Example to compare the size of uninitialized data segment(bss)
Example to compare the size of uninitialized data
segment(bss)
Data Structure
Data Structure refer to the organization and management of
data in a way that enables efficient access and modification.

Data Structure is a particular way of storing and organizing data


in the memory of the computer so that these data can easily be
retrieved and efficiently utilized in the future when required.

24
Importance of Data Structure
• Data structures allow storing the information on hard disks.
• An appropriate choice of data structure makes the program
more efficient.
• Data Structures are necessary for designing efficient algorithms.
• Using appropriate data structures can help programmers save a
good amount of time while performing operations such as
storage, retrieval, or processing of data.
• Manipulation of large amounts of data is easier.

25
Classification of Data Structure

26
Primitive and non-primitive data structure
• Primitive data structure is a fundamental type of data structure
that stores the data of only one type whereas the non-
primitive data structure is a type of data structure that stores
the data of different types in a single entity.
• Examples of primitive data structure: int, float, char
• Examples of non-primitive data structure: array, linked list,
queue, etc.

27
Difference between Linear and Non-linear Data Structures
Linear Data Structure:

Linear data structure: Data structure in which data elements are arranged sequentially or
linearly, where each element is attached to its previous and next adjacent elements, is
called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.

• Static data structure: Static data structure has a fixed memory size. It is easier to
access the elements in a static data structure.
An example of this data structure is an array.
• Dynamic data structure: In the dynamic data structure, the size is not fixed. It can be
randomly updated during the runtime which may be considered efficient concerning the
memory (space) complexity of the code.
Examples of this data structure are queue, stack, etc. 28
Difference between Linear and Non-linear Data Structures

Non-linear Data Structure:

Data structures where data elements are not placed sequentially or linearly are
called non-linear data structures. In a non-linear data structure, we can’t
traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs.

Non-linear data structures are not easy to implement in comparison to linear


data structure.

It utilizes computer memory efficiently in comparison to a linear data structure.


29
Difference between Linear and Non-linear Data Structures:
S.NO Linear Data Structure Non-linear Data Structure

In a linear data structure, data elements are


arranged in a linear order where each and every In a non-linear data structure, data
1. elements is attached to its previous and next elements are attached in hierarchically
adjacent. manner.

2. In linear data structure, single level is involved. Whereas in non-linear data structure,
multiple levels are involved.

3. Its implementation is easy in comparison to non- While its implementation is complex in


linear data structure. comparison to linear data structure.

While in non-linear data structure, data


4. In linear data structure, data elements can be elements can’t be traversed in a single run
traversed in a single run only. only.

While in a non-linear data structure,


5. In a linear data structure, memory is not utilized memory is utilized in an efficient way.
in an efficient way.

Its examples are: array, stack, queue, linked list,


6. etc. While its examples are: trees and graphs.

30
Array
An array is a linear data structure and it is a collection of items
stored at contiguous memory locations.
The idea is to store multiple items of the same type together in
one place. It allows the processing of a large amount of data in a
relatively short period. The first element of the array is indexed
by a subscript of 0.
There are different operations possible in an array, like Searching,
Sorting, Inserting, Traversing, Reversing, and Deleting.

31
32
Linked List
A linked list is a linear data structure in which elements are not stored at
contiguous memory locations. The elements in a linked list are linked using
pointers as shown in the below image:

Types of linked lists:

• Singly-linked list
• Doubly linked list
• Circular linked list
• Doubly circular linked list
33
34
Key Differences Between Array and Linked List
1. An array is the data structure that contains a collection of similar type of data elements whereas the
Linked list is considered as non-primitive data structure that contains a collection of unordered
linked elements known as nodes.

2. In the array the elements belong to indexes, i.e., if you want to get into the fourth element you have
to write the variable name with its index or location within the square bracket.

3. In a linked list though, you have to start from the head and work your way through until you get to
the fourth element.

4. Accessing an element in an array is fast, while Linked list takes linear time, so it is quite a bit slower.

5. Operations like insertion and deletion in arrays consume a lot of time. On the other hand, the
performance of these operations in Linked lists is fast.

35
Key Differences Between Array and Linked List
6. Arrays are of fixed size. In contrast, Linked lists are dynamic and flexible and can expand and
contract its size.

7. In an array, memory is assigned during compile time while in a Linked list it is allocated
during execution or runtime.

8. Elements are stored consecutively in arrays whereas it is stored randomly in Linked lists.

9. The requirement of memory is less due to actual data being stored within the index in the
array. As against, there is a need for more memory in Linked Lists due to storage of
additional next and previous referencing elements.

10. In addition memory utilization is inefficient in the array. Conversely, memory utilization is
efficient in the linked list.
36
Stack
Stack is a linear data structure that follows a particular order in
which the operations are performed. The order is LIFO(Last in
first out). Entering and retrieving data is possible from only one
end. The entering and retrieving of data is also called push and
pop operation in a stack.

37
38
Queue
Queue is a linear data structure that follows a particular order in
which the operations are performed. The order is First In First
Out (FIFO) i.e. the data item stored first will be accessed first. In
this, entering and retrieving data is not done from only one end.

An example of a queue is any queue of consumers for a resource


where the consumer that came first is served first.

39
40
Tree
A tree is a non-linear and hierarchical data structure where the
elements are arranged in a tree-like structure. In a tree, the topmost
node is called the root node. Each node contains some data, and data
can be of any type. It consists of a central node, structural nodes, and
sub-nodes which are connected via edges.

Different tree data structures allow quicker and easier access to the
data as it is a non-linear data structure. A tree has various
terminologies like Node, Root, Height of a tree, Degree of a tree, etc.
41
42
Graph
A graph is a non-linear data structure that consists of vertices (or
nodes) and edges. It consists of a finite set of vertices and set of
edges that connect a pair of nodes. The graph is used to solve the
most challenging and complex programming problems.

43
44
Advantages of Data Structure
Advantages of data structure:
• Improved data organization and storage efficiency.
• Faster data retrieval and manipulation.
• Facilitates the design of algorithms for solving complex problems.
• Eases the task of updating and maintaining the data.
• Provides a better understanding of the relationships between data
elements.

45
Disadvantages of Data Structure
Disadvantages of Data Structure:
• The more the application or data structure involved in creating and maintaining the
application, the greater the labor supply. This can increase the expense of maintaining
data structures. The more complex the program, the more similar data structures will
be involved. For example, we may access data structures such as a cluster, line, stack,
connected list, tree, chart, etc. As a result, you may need a few professionals to create
and maintain the program.
• Complexity in debugging and testing.
• Difficulty in modifying existing data structures.
• Larger applications necessitate data structures within each other, just like the hub of a
chart is made up of an exhibit or a rundown. As a result, maintenance is both puzzling
and costly in such cases.
46
Common operations on various Data Structures
• Traversing: Traversing a Data Structure means to visit the element stored in it. It
visits data in a systematic manner.
• Searching: Searching means to find a particular element in the given data-
structure. It is considered as successful when the required element is found.
Searching is the operation which we can performed on data-structures like array,
linked-list, tree, graph, etc.
• Insertion: It is the operation which we apply on all the data-structures. Insertion
means to add an element in the given data structure.
• Deletion: It is the operation which we apply on all the data-structures. Deletion
means to delete an element in the given data structure.
• Sorting: Sorting data in a particular order (ascending or descending).
47
Memory Allocations in Data Structures

Memory allocation is the process of setting aside sections of


memory in a program to be used to store variables, and instances
of structures and classes.
There are two types of memory allocations possible in C:

1.Compile-time or Static allocation.


2.Run-time or Dynamic allocation (using pointers).

48
Compile-time or Static allocation

Static memory allocation allocated by the compiler. Exact size and


type of memory must be known at compile time.

When the first statement is encountered, the compiler will allocate


two bytes to each variables x and y. The second statement results
into the allocation of 20 bytes to the array a (5*4, where there are
five elements and each element of float type takes four bytes).
49
Run-time or Dynamic allocation

Dynamic memory allocation is when an executing program requests that the


operating system give it a block of main memory. The program then uses this
memory for some purpose. Usually the purpose is to add a node to a data structure.

C provides the following dynamic allocation and de-allocation functions :


• malloc( )
• calloc( )
• free( )
• realloc( )

50
Garbage Collection in Data Structure
• A memory management technique called garbage collection
automatically identifies and releases memory that is no longer
used by a program. Garbage collection makes it unnecessary
for the programmer to manage memory manually, which lowers
the risk of memory leaks and segmentation errors.
• Garbage collection frees the programmer from having to
deallocate and return objects to the memory system manually.
Garbage collection can account for a considerable amount of a
program's total processing time, and as a result, can have a
significant impact on performance.
51
• In older programming languages, such as C and C++, the developer must manually delete
objects and free up memory. Relying on manual processes made it easy to introduce bugs into
the code, some of which can have serious consequences.

• For example, a developer might forget to free up memory after the program no longer needs it,
leading to a memory leak that quickly consumes all the available RAM. Or the developer might
free up an object's memory space without modifying a corresponding pointer, resulting in a
dangling pointer that causes the application to be buggy or even to crash.

• Programming languages that include garbage collection try to eliminate these types of bugs by
using carefully designed GC algorithms to control memory deallocation. The garbage collector
automatically detects when an object is no longer needed and removes it, freeing up the memory
space allocated to that object without affecting objects that are still being used.

52
Memory Leak
• https://www.geeksforgeeks.org/what-is-memory-leak-how-
can-we-avoid/

53
Different types of pointers
• https://www.geeksforgeeks.org/dangling-void-null-wild-
pointers/

54
Storage Compaction
• Storage compaction is another technique for reclaiming free
storage. Compaction works by actually moving blocks of data
from one location in the memory to another so as to collect all
the free blocks into one single large block.

55
Iterative Approach
In programming specifically, iterative refers to a sequence of instructions or code
being repeated until a specific end result is achieved.

56
Recursive Approach
A recursive algorithm calls itself with smaller input values and
returns the result for the current input by carrying out basic
operations on the returned value for the smaller input. Generally,
if a problem can be solved by applying solutions to smaller
versions of the same problem, and the smaller versions shrink to
readily solvable instances, then the problem can be solved using a
recursive algorithm.

57
To build a recursive algorithm, you will break the given problem
statement into two parts. The first one is the base case, and the
second one is the recursive step.
• Base Case: It is nothing more than the simplest instance of a
problem, consisting of a condition that terminates the recursive
function. This base case evaluates the result when a given
condition is met.
• Recursive Step: It computes the result by making recursive
calls to the same function, but with the inputs decreased in size
or complexity.

58
• For example, consider this problem statement: Print sum of n natural
numbers using recursion. This statement clarifies that we need to formulate
a function that will calculate the summation of all natural numbers in the
range 1 to n. Hence, mathematically you can represent the function as:
• F(n) = 1 + 2 + 3 + 4 + …………..+ (n-2) + (n-1) + n

59
60
References
• Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.;
Stein, Clifford (2009). Introduction to Algorithms, Third
Edition (3rd ed.). The MIT Press. ISBN 978-0262033848.
• Seymour, Lipschutz (2014). Data structures (Revised first ed.).
New Delhi, India: McGraw Hill Education. ISBN
9781259029967. OCLC 927793728.

61

You might also like