0% found this document useful (0 votes)
27 views73 pages

Data Structure - Module-1 Notes

The document provides an introduction to arrays in C, detailing their types, declarations, and advantages. It covers one-dimensional, two-dimensional, and multidimensional arrays, including their initialization, accessing elements, and use cases. Additionally, it explains character arrays and pointers, highlighting their significance in memory management and function handling.

Uploaded by

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

Data Structure - Module-1 Notes

The document provides an introduction to arrays in C, detailing their types, declarations, and advantages. It covers one-dimensional, two-dimensional, and multidimensional arrays, including their initialization, accessing elements, and use cases. Additionally, it explains character arrays and pointers, highlighting their significance in memory management and function handling.

Uploaded by

joginvarsha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays- Introduction

• An array is a collection of variables of the same data type


stored in contiguous memory locations.
• It allows easy access and manipulation of multiple values using
a single identifier.
Advantages of Arrays
•Enables storing multiple values under one name.
•Provides efficient memory management.
•Allows easy traversal using loops.
•Supports sorting, searching, and other operations efficiently.
Declaration of Arrays

Arrays in C are declared using the following syntax:

data_type array_name[size];
Example:

int numbers[10]; // Declares an array of 10 integers


One-Dimensional Arrays

• A one-dimensional array is a linear list of elements, each of which


is accessed using an index.
Syntax:
data_type array_name[size];

int marks[5]; // Array to store 5 integers


Assigning Values
marks[0]=50;
:
:
marks[4]=20;
Initialization of One-Dimensional
Arrays
• Arrays can be initialized in multiple ways:
[Link] the time of declaration
int marks[5] = {90, 85, 78, 92, 88};
[Link] Initialization
int scores[5] = {10, 20};
// Remaining elements will be initialized to 0.
3. Without specifying size
int values[] = {5, 10, 15, 20};
// Compiler determines the size automatically.
• 1D array
can be
initialized
using the
scanf()
function
by
reading
user input
for each
element.
Accessing Elements in an Array

• Array elements are accessed using an index (starting from 0).


Example:
int arr[3] = {10, 20, 30};
printf("%d", arr[0]); // Output: 10
• Traversing an Array
Using loops to iterate through an array:
int i;
for(i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
Use Cases of 1D Arrays
Best for: Simple Lists and Linear Data Storage
A 1D array is a single list of elements stored sequentially in
memory. It is the most basic type of array.

1. Storing Student Marks


int marks[5] = {90, 85, 78, 92, 88};
2. Storing a List of Names or Characters
char name[] = "Mohammed";
Used for strings in C.
Two-Dimensional Arrays
• A two-dimensional array is an array of arrays, also known as a
matrix.
Declaration of Two-Dimensional Arrays
data_type array_name[rows][columns];
Example:
int matrix[3][3]; // 3x3 matrix
Assigning values
matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3; matrix[1][0] = 4;
matrix[1][1] = 5; matrix[1][2] = 6; matrix[2][0] = 7; matrix[2][1] = 8;
matrix[2][2] = 9;
Array shape:
123
456
789
Initialization of Two-Dimensional
Arrays
• Two-dimensional arrays can be initialized in various ways:
[Link]-wise Initialization
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
2. Compact Initialization
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
// Compiler arranges in row-major order.
3. Partial Initialization
int matrix[3][3] = { {1, 2}, {3, 4} };
// Remaining values set to 0
Using scanf with a 2D Array in C
Accessing Elements of a Two-Dimensional Array
printf("%d", matrix[0][1]);
// Accesses element at row 0, column 1.
Traversing a Two-Dimensional Array
int i, j;
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
} printf("\n");
}
Use Cases of 2D Arrays
• Best for: Tabular Data, Grids, and Matrices.

1. Storing and Processing Matrices


2. Image Processing (Grayscale Images)
• 2D arrays store pixel intensities of grayscale images (Black & White).
3. Storing Database Records (Row & Column Format)
• Example: Student Records (ID, Name, Marks in different subjects).
Multidimensional Arrays
• Arrays with more than two dimensions are called
multidimensional arrays.
Declaration of a Multidimensional Array
data_type array_name[size1][size2][size3]...[sizeN];
Example
int tensor[2][2][2]; // 3D array with 2x2x2 elements ((2 layers, 2
rows, 2 columns))
• A 3D array is an array of 2D arrays, meaning it consists of
multiple 2D arrays stacked together.
What is a 3D Array?
• A 3D array can be thought of as a collection of matrices
(tables), where:
• The first dimension represents different layers.
• The second dimension represents rows.
• The third dimension represents columns.
• Syntax for Declaring a 3D Array

type array_name[size1][size2][size3];

where:
•size1 → Number of layers.
•size2 → Number of rows per layer.
•size3 → Number of columns per row.
Example 3D Array
Representation:

Layer 1:
12
34

Layer 2:
56
78
What Does "Layers" Mean in Multi-Dimensional Arrays?
• In multi-dimensional arrays, a layer refers to a group of rows
and columns at a particular depth level.
• Think of it as stacking multiple 2D arrays on top of each
other to form a 3D structure.
• A 2D array is like a table with rows and columns. When you
extend this into 3D, you get multiple 2D arrays stacked
together, where each stack is called a layer.
• Initializing a Multidimensional Array

int cube[2][2][2] = { { {1, 2}, {3, 4} },


{ {5, 6}, {7, 8} } };
Accessing Elements in a Multidimensional Array
printf("%d", cube[1][0][1]); // Accessing element at
cube[1][0][1]

For example:
array[0][0][0] → (1st layer, 1st row, 1st column)
array[1][2][1] → (2nd layer, 3rd row, 2nd column)
array[2][1][2] → (3rd layer, 2nd row, 3rd column)
• Traversing a 3D Array
int i, j, k;
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
for(k = 0; k < 2; k++) {
printf("%d ", cube[i][j][k]); }
printf("\n"); }
printf("\n"); }
#include <stdio.h> // Displaying the 3D array
printf("3D Array
int main() { Representation:\n");
int data[2][3][3]; // 3D array with 2 for (int l = 0; l < 2; l++) {
layers, 3 rows, 3 columns printf("\n=== Layer %d ===\n", l
+ 1);
// Initializing the 3D array for (int r = 0; r < 3; r++) {
int value = 1; for (int c = 0; c < 3; c++) {
for (int l = 0; l < 2; l++) { // Layers printf("%d ", data[l][r][c]);
for (int r = 0; r < 3; r++) { // Rows }
for (int c = 0; c < 3; c++) {// printf("\n"); // New line after
Columns each row
data[l][r][c] = value++; }
} }
}
} return 0;
}
• Use Cases of 3D Arrays
[Link] Imaging (CT Scans, MRI Scans)
1. Used to store 3D medical scans, where each slice is a 2D image.
2.3D Graphics and Computer Vision
1. Used for storing RGB color images (each pixel has Red, Green, Blue
values).
• int image[1920][1080][3]; // RGB image storage
4D Array

• A 4D array is an array with four dimensions, meaning it


consists of multiple 3D arrays stacked together.
• Syntax for Declaring a 4D Array
type array_name [size1][size2][size3][size4];
where:
•size1 → Number of super blocks (highest level).
•size2 → Number of groups within each super block.
•size3 → Number of rows in each group.
•size4 → Number of columns in each row.
#include <stdio.h> // Displaying the 4D array
printf("4D Array Representation:\n");
int main() { for (int s = 0; s < 2; s++) {
int data[2][2][2][2]; // 4D array with printf("\n=== Super Block %d ===\n", s
small dimensions + 1);
for (int g = 0; g < 2; g++) {
// Initializing the 4D array printf("\n Group %d:\n", g + 1);
int value = 1; for (int r = 0; r < 2; r++) {
for (int s = 0; s < 2; s++) { // Super for (int c = 0; c < 2; c++) {
Blocks printf("%d ", data[s][g][r][c]);
for (int g = 0; g < 2; g++) { // }
Groups printf("\n");
for (int r = 0; r < 2; r++) { // Rows }
for (int c = 0; c < 2; c++) { // }
Columns }
data[s][g][r][c] = value++;
} return 0; }
}
Real-World Applications of 4D Arrays

1. Deep Learning (AI & Machine Learning)


•TensorFlow & PyTorch use 4D tensors for image processing.
•Example: [Batch Size][Height][Width][Channels].

2. Video Processing (Frame Sequences)


•A 4D array represents multiple frames of a video
•video[frames][rows][columns][RGB channels]
•int video[30][1080][1920][3]; // 30 frames of 1080p video (RGB)

3. Medical Imaging (CT Scans, MRI, 4D Ultrasound)


• Tracks changes over time using a 4D dataset.
• scan[time][slice][row][column]
Character Arrays in C
• A character array is a collection of characters stored in
contiguous memory locations. In C programming, character
arrays are commonly used to store and manipulate strings.
1. Declaring a Character Array
• A character array can be declared like any other array.
char array_name[size];
Example:
char letters[5]; // A character array of size 5
This array can hold 5 characters. Each element is a single
character (char).
2. Initializing a Character Array

• A character array can be initialized in different ways:


Method 1: Character-by-Character Initialization
char word[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
• The null terminator '\0' is required to indicate the end of a
string.
Method 2: String Initialization
char word[] = "Hello";
• The compiler automatically adds \0 at the end.
4. Printing a Character Array
#include <stdio.h>

int main() {
char word[] = "Hello";
printf("String: %s\n", word);
return 0;
}
Output:
String: Hello // %s prints characters until \0 is
found.
Pointers in C
Introduction to Pointers
• A pointer is a variable that stores the memory address of another
variable. Instead of storing values directly, it stores the location
(address) of the value in memory.
Declaration of a Pointer
data_type *pointer_name;
Here *(asterisk) denotes a pointer. data_type specifies the type of data
it points to.
Example
int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float
Pointer Concepts
• Address-of operator (&): Gets the memory address of a variable.
• Dereference operator (*): Accesses the value stored at the pointer’s address.

#include <stdio.h>
int main() {
int num = 10;
int *ptr = &num; // Pointer stores the address of Output:
num Value of num: 10
printf("Value of num: %d\n", num); Address of num:
printf("Address of num: %p\n", &num); 0x7ffeefbff6dc
printf("Pointer stores: %p\n", ptr); Pointer stores: 0x7ffeefbff6dc
printf("Value accessed via pointer: %d\n", *ptr); // Value accessed via pointer:
Dereferencing 10
return 0;
}
Accessing Variables through Pointers
• A pointer allows you to modify the value of a variable indirectly.
#include <stdio.h>

int main() {
int x = 5; Output:
int *ptr = &x; Before: x = 5
printf("Before: x = %d\n", x); After: x = 20
*ptr = 20; // Changing value via pointer
printf("After: x = %d\n", x);
return 0;
}
Pointer Applications
(A) Arrays and Pointers
• An array name itself acts as a pointer to the first element.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30}; Output:
int *ptr = arr; // Pointer to the first First element: 10
element Second element: 20
printf("First element: %d\n", *ptr); Third element: 30
printf("Second element: %d\n", *(ptr +
1));
printf("Third element: %d\n", *(ptr + 2));
return
• arr is not0; }
a variable, but a constant pointer to the first element of the array.
• The expression arr already holds the memory address of arr[0].
• Ie arr represents the address of the first element (&arr[0]).
B. Pointer to Function
Pointers can be used to call functions dynamically.
Memory Layout of a C- program
• When a C program runs, it requires memory allocation in RAM
(Random Access Memory).
• The operating system (OS) assigns memory to the program in
a structured manner, dividing it into segments.
What is a Function Pointer?
• A function pointer is a pointer that stores the memory address of
a function instead of a variable. It allows functions to be called
dynamically.
Memory Representation of a Function
When a function is declared/defined in C:

void display() {
printf("Hello from function pointer!\n"); }

• It is stored in the Code Segment of memory.


• The function name ‘display’ represents the starting memory
address of its executable code. Just like variables, functions also
have addresses.
Declaring a Function Pointer
• A function pointer must have:
• The same return type as the function.
• The same parameters as the function.
return_type (*pointer_name)(parameter_list);
Example:
void (*funcPtr)(); // Function pointer declaration
• void → Return type (same as the function ‘display’).
• (*funcPtr) → Declares a pointer variable, ‘funcPtr’ that can store a
function's address.
• ( ) → Represents that the function takes no parameters.
Assigning a Function Address
• A function pointer can be assigned without the ‘&’ operator
(because function names act as pointers):
funcPtr = display; // Assign function address
Equivalent (but not required):
funcPtr = &display;
Calling a Function Using Pointer
• Once a function pointer holds a function’s address, we can call
it using:
funcPtr(); // Calls display()
Equivalent:
(*funcPtr)();
#include <stdio.h>
// Function to be called using a function pointer
Output:
void display() { Hello from function
printf("Hello from function pointer!\n"); pointer!
}
int main() {
void (*funcPtr)(); // Declaring a function pointer
funcPtr = display; // Assign function address to pointer
funcPtr(); // Calling function using pointer

return 0;
}
Dynamic Memory Allocation
functions in C
What is Dynamic Memory Allocation
• Dynamic Memory Allocation allows memory to be allocated
at runtime instead of compile time. This is useful when we
don’t know the exact memory size needed beforehand.
• Memory is allocated in the heap section.
• Returns the address of the allocated memory's first byte to
a pointer.
• All these functions are found in the <stdlib.h> library.
• Must be deallocated using free() to avoid memory loss after
use.
Functions for Dynamic Memory Allocation
malloc() – Memory Allocation

✔ malloc() (Memory ALLOCation) dynamically allocates a block


of memory.
✔ It returns the address of the allocated memory's first byte
to a pointer.
✔ The allocated memory is uninitialized (contains garbage
values).
✔ If memory allocation fails, malloc() returns NULL.
Syntax ptr = (type*) malloc(size);
size is the number of bytes to allocate.
Typecasting ((type*)) ensures correct pointer type. By default, it is
void.
Example 1: malloc Allocating Memory for an int variable
#include <stdio.h>
#include <stdlib.h> • malloc()
int main() { returns the
int *ptr; address of
ptr = (int*) malloc(sizeof(int)); // Allocate memory for 1 the allocated
integer memory.
if (ptr == NULL) { // Check if malloc() succeeded • ptr stores this
printf("Memory allocation failed!\n"); starting
return 1; } address.
*ptr = 100; // Store a value
printf("Stored int value: %d\n", *ptr); • *ptr accesses
printf("Memory address allocated: %p\n", ptr); and stores the
return 0; } actual value.

Output: Stored int value: 100


Memory address allocated: 0x600003e70 (Example address)
Example 2: malloc Allocating Memory for a float variable

#include <stdio.h>
#include <stdlib.h>
int main() {
float *ptr; // Declare a pointer to float
ptr = (float*) malloc(sizeof(float)); // Allocate memory for 1 float
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*ptr = 3.14; // Storing a float value in allocated memory
printf("Stored float value: %.2f\n", *ptr);
printf("Memory address allocated: %p\n", ptr); // Print memory address
return 0; }
Output: Stored float value: 3.14
Memory address allocated: 0x600003e71 (Example address)
calloc() – Contiguous Allocation

✔ calloc() (Contiguous ALLOCation) dynamically allocates multiple


memory blocks.
✔ Unlike malloc(), calloc() initializes all memory locations to 0.
✔ It is useful when we need multiple elements (arrays, matrices, etc.).
Syntax:

ptr = (type*) calloc(n, size);


n → Number of elements to allocate.
size → Size of each element in bytes
Example: Allocating Memory for 5 int Values

#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, i; malloc()
arr = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers does not
if (arr == NULL) { initialize
printf("Memory allocation failed!\n"); memory,
return 1;
but calloc()
}
printf("Array elements after calloc(): "); sets all
for (i = 0; i < 5; i++) { values to
printf("%d ", arr[i]); // All elements should be 0 0.
}
return 0;}

Output: Array elements after calloc(): 0 0 0 0 0


realloc() – Resize Allocated Memory

✔ realloc() (RE-ALLOCation) resizes a previously allocated memory


block.
✔ Useful when we need more memory or want to shrink the
allocated memory.
✔ Can increase or decrease allocated memory.
Syntax:
ptr = (type*) realloc(ptr, newSize);
• ptr → Pointer to previously allocated memory.
• newSize → New size in bytes.
• Returns new address of allocated memory.
Example: Expanding Memory Using realloc()

#include <stdio.h> printf("Original values: ");


#include <stdlib.h> for (i = 0; i < 3; i++) {
printf("%d ", ptr[i]);
int main() { }
int *ptr, i; // Step 3: Resize memory from 3 to 5 integers
ptr = (int*) realloc(ptr, 5 * sizeof(int));
// Step 1: Allocate memory for 3 integers if (ptr == NULL) {
ptr = (int*) malloc(3 * sizeof(int)); printf("Memory reallocation failed!\n");
return 1;
if (ptr == NULL) { }
printf("Memory allocation failed!\n"); // Step 4: Assign new values for extended part
return 1; for (i = 3; i < 5; i++) {
} ptr[i] = (i + 1) * 10; // Assign values: 40, 50
}
// Step 2: Assign values printf("\nExpanded values: ");
for (i = 0; i < 3; i++) { for (i = 0; i < 5; i++) {
ptr[i] = (i + 1) * 10; // Assign values: 10, 20, 30 printf("%d ", ptr[i]);
} }

return 0; }
ptr[i] is equivalent to *(ptr + i)
free() – Deallocate Memory

• free() releases dynamically allocated memory, preventing


memory leaks (loss).
✔ After freeing, set the pointer to NULL to avoid dangling pointers.
• A dangling pointer is a pointer that points to a memory location
that has been freed or deleted, ie the pointer itself still holds the
old address.

• Syntax
free(ptr);
ptr = NULL; // Avoids dangling pointer issues
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int*) malloc(sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*ptr = 55;
printf("Value stored: %d\n", *ptr);

free(ptr); // Free memory


ptr = NULL; // Avoid dangling pointer

return 0;}
Structures and Unions
In C programming, structures and unions allow grouping multiple
variables of different types under one name.
Introduction to Structures
✔ A structure (struct) is a user-defined data type that allows
storing multiple variables of different types together.
✔ Useful for representing real-world entities (e.g., student
details, employee records).
Declaring a Structure
✔ We define a structure using the ‘struct’ keyword.
#include <stdio.h>

// Define a structure
struct Student {
int roll_no;
char name[50];
float marks;
};

int main() {
struct Student s1; // Declaring a
structure variable
return 0;
}

Here, Student contains three members: roll_no, name, and


marks.
#include <stdio.h>
Giving Values to struct Student {
int roll_no;
Structure Members char name[50];
float marks;
};
• ✔ Structure members do not get int main() {
default values (must be assigned struct Student s1;
manually).
// Assign values to structure members
s1.roll_no = 101;
[Link] = 89.5;
// String assignment Use strcpy() to assign
values to char arrays inside structures.
strcpy([Link], “six sem ece");

// Print structure members


Output: printf("Roll No: %d\n", s1.roll_no);
Roll No: 101 printf("Name: %s\n", [Link]);
Name: John Doe printf("Marks: %.2f\n", [Link]);
Marks: 89.50 return 0;}
#include <stdio.h>
Structure Initialization
struct Student {
int roll_no;
✔ We can initialize structures char name[50];
at declaration time. float marks;
};

int main() {

// Initialization
struct Student s1 = {101, "John Doe",
89.5};
printf("Roll No: %d\n", s1.roll_no);
Order matters! {101, "John Doe", 89.5} printf("Name: %s\n", [Link]);
matches {int, char[], float}. printf("Marks: %.2f\n", [Link]);

return 0;
Comparison of #include <stdio.h>
#include <string.h>

Structure Variables struct Student {


int roll_no;
char name[50];
float marks;
• Direct comparison (s1 == s2) is not
};
possible!
✔ Instead, compare each member
separately. int main() {
struct Student s1 = {101, "John Doe", 89.5};
struct Student s2 = {102, "Jane Smith", 78.0};
Use strcmp() for comparing strings
inside structures. if (s1.roll_no == s2.roll_no && strcmp([Link],
[Link]) == 0 && [Link] == [Link]) {
printf("Both students are identical.\n");
} else {
printf("Students are different.\n");
}

return 0;
}
Arrays of Structures
#include <stdio.h>

struct Student {
• A structure can be int roll_no;
char name[50];
used as an array to float marks;
store multiple records. };

• Useful for handling int main() {


multiple records struct Student students[2] = {
efficiently! {101, "John Doe", 89.5},
{102, "Jane Smith", 78.0}
};

for (int i = 0; i < 2; i++) {


printf("Roll No: %d, Name: %s,
Marks: %.2f\n", students[i].roll_no,
students[i].name, students[i].marks);
}

return 0;}
Arrays Within
Structures Example: Storing Multiple Subjects' Marks
#include <stdio.h>

• ✔ A structure can struct Student {


int roll_no;
contain an array as
char name[50];
a member. float marks[3]; // Array inside structure
• Allows storing };
multiple values inside
int main() {
a structure field. struct Student s1 = {101, "John Doe", {90.5, 85.0, 88.0}};

printf("Marks: %.2f, %.2f, %.2f\n", [Link][0],


[Link][1], [Link][2]);

return 0;
}
Nested Example: Student with Address Structure
#include <stdio.h>
Structures struct Address {
char city[50];
• A structure inside char state[50];
};
another structure.
• Allows better struct Student {
organization of complex int roll_no;
char name[50];
data structures. struct Address address; // Nested Structure
};

int main() {
struct Student s1 = {101, "John Doe", {"New York",
"NY"}};

printf("Student: %s, City: %s, State: %s\n", [Link],


[Link], [Link]);
Union
Example: Using a Union

#include <stdio.h>

s union Data {
int i;
• A union is similar float f;
to a structure, but char str[20];
all members share };
the same memory
int main() {
location. union Data data;
• Saves memory
but only one data.i = 10;
member can store printf("Integer: %d\n", data.i);
a value at a time.
data.f = 3.14; // Overwrites previous value
• Each assignment printf("Float: %.2f\n", data.f);
overwrites the
previous value. strcpy([Link], "Hello"); // Overwrites previous value
printf("String: %s\n", [Link]);
return 0; }
Example: Checking Size of Structure

Size of Structures
#include <stdio.h>

struct Test {
char a;
int b;
• The size of a double c;
structure depends };
on padding &
alignment. int main() {
printf("Size of struct: %lu bytes\n",
• Due to memory sizeof(struct Test));
alignment, the return 0;
}
structure may take
more space than • sizeof() is an operator that returns the size in bytes of

expected. a data type or variable.


• sizeof(struct Test) gives the memory occupied by the
%lu (Format Specifier) → Prints an struct Test.
unsigned long int. %lu ensures correct • sizeof(struct Test) calculates the total bytes occupied by
formatting of sizeof() output. members (char, int, double) including padding.
What is Padding?
• Padding is the extra unused memory added between
structure members to satisfy alignment rules.
✔ The compiler inserts padding bytes to ensure efficient
memory access.
✔ Padding increases the structure size, but improves
performance.

You might also like