Module 1
Module 1
(Open Elective)
Module -1
Arrays: Introduction, One-Dimensional Arrays, Two-Dimensional Arrays, Initializing
Two- Dimensional Arrays, Multidimensional arrays.
Pointers: Introduction, Pointer Concepts, Accessing Variables through Pointers, Pointer
Applications, Dynamic Memory Allocation Functions.
Structures and Unions: Introduction, Declaring Structures, Giving Values to Members,
Structure Initialization, Comparison of Structure Variables, Arrays of Structures, Arrays
within Structures, Nested Structures, Unions, Size of Structures.
Text Books:
Data structures using C , E Balagurusamy, McGraw Hill education (India) Pvt. Ltd, 2013.
Textbook 1: Ch. 8.1 to 8.5, Ch. 12.1 to 12.8, 12.10, 12.11.
Textbook 2: Ch. 2.1 to 2.3, 2.5, 2.9.
Lecture 01:
C Programming: Overview
C is a powerful, general-purpose programming language developed in the early 1970s by Dennis Ritchie at Bell Labs. It remains
the foundation of many modern programming languages due to its speed, portability, and closeness to hardware.
🔹 Key Features
• Low-level access to memory with pointers
• Modular structure using functions
• Rich set of built-in operators and libraries
• Highly portable across platforms
• Efficient for system-level programming
🔹 Use Cases
• Operating systems (e.g., UNIX, Linux kernels)
• Embedded systems and microcontrollers
• Compilers and interpreters
• Device drivers and firmware
🔹 Basic Syntax Elements
Element Description
#include Preprocessor directive for libraries
main() Entry point for execution
printf() / scanf() Input-output functions
int, char, etc. Data types
{} Blocks of code
🔹 Sample Code
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
This minimal C program prints "Hello, World!" and demonstrates the structure of a typical C program.
Use the terminal settings -> select the terminal and do necessary setting to further style your terminal like transparency:
Viva Questions
How do you debug a program within VS Code using breakpoints and watch expressions?
What is the role of the integrated terminal in VS Code, and how is it useful for development?
How can you create and use code snippets in VS Code to speed up coding tasks?
What is the difference between a workspace and a folder in VS Code?
Lecture 03:
Introduction to Arrays
An array is a fundamental data structure in C programming, used to store multiple variables of the same type in a
single entity. These variables, also known as elements, are stored in contiguous memory locations, which means
that each element is placed sequentially in memory.
Arrays are particularly useful when you need to work with a large collection of data without having to declare
individual variables for each item. They allow efficient storage, retrieval, and manipulation of data using
indexing.
Advantages of Using Arrays:
Efficient Storage: Arrays allow you to store a large number of elements without needing to declare separate
variables for each one.
Easy Access: Elements in an array can be accessed quickly using their index.
Iteration: Arrays are suitable for use with loops, making it easy to iterate over all elements.
Syntax:
data_type array_name[array_size];
data_type: The type of data the array will hold (e.g., int, float, char).
array_name: The name you give to the array.
array_size: The number of elements the array can hold.
Example:
int numbers[5]; // Declares an array named 'numbers' that can hold 5 integers
`int` is the data type, indicating that the array will hold integer values.
`numbers` is the name of the array.
`[5]` specifies that the array will contain 5 elements, indexed from 0 to 4.
Accessing Array Elements:
To access or modify elements in an array, you use the index of the element. Array indices start at 0.
numbers[0] = 10; // Assigns the value 10 to the first element of the array
printf("%d", numbers[0]); // Prints the first element of the array, which is 10
One-Dimensional Arrays
A one-dimensional array is a type of array that stores a sequence of elements. These elements are all of the same
data type and are stored in contiguous memory locations. Each element in the array can be accessed directly
using its index, which starts from 0 and goes up to (array size - 1).
One-dimensional arrays are particularly useful when you need to manage and manipulate lists of data in an
organized manner. They simplify the process of working with multiple related variables by storing them all in
one structure.
Syntax:
data_type array_name[array_size];
data_type: The type of elements that the array will hold (e.g., `int`, `float`, `char`).
array_name: The name you give to the array.
array_size: The number of elements the array can hold.
Example:
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50}; // Initializing an array of 5 integers
// Looping through the array to print each element
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation:
Declaration and Initialization: `int arr[5] = {10, 20, 30, 40, 50}; This line declares an array `arr` of type `int` that
can hold 5 elements. The array is initialized with values 10, 20, 30, 40, and 50 respectively.
Accessing Elements: `arr[i]`. The `for` loop iterates through the array using the index `i` to access each element.
The `printf` function prints each element followed by a space.
Modifying Elements:
You can also modify the elements of the array using their index.
arr[0] = 15; // Modifies the first element to 15
arr[3] = 35; // Modifies the fourth element to 35
Use Cases:
- Storing lists of values, such as temperatures, scores, or inventory items.
- Performing mathematical computations on a series of numbers.
- Implementing algorithms that require a collection of elements, such as searching and sorting.
Summary:
one-dimensional arrays are versatile data structures that make it easy to manage and manipulate collections of
related data elements efficiently. They form the basis for more complex data structures and are fundamental in
programming.
Viva Questions
What is the syntax for declaring and initializing a one-dimensional array in C?
How is memory allocated for a one-dimensional array, and how are elements accessed?
Can the size of a one-dimensional array be changed after its declaration? Why or why not?
What happens if you try to access an index outside the bounds of the array?
Lecture 04:
Two-Dimensional Arrays
A two-dimensional array is essentially an array of arrays. This means that each element of a two-dimensional
array is itself an array. They are particularly useful for representing data in a tabular format, like a matrix or a
table. Each element can be accessed using two indices: one for the row and one for the column.
Key Points:
Structure: A two-dimensional array is structured as rows and columns.
Indexing: It uses two indices to access elements: the first index represents the row, and the second
index represents the column.
Initialization: It can be initialized at the time of declaration.
Syntax:
data_type array_name[rows][columns];
data_type: The type of elements that the array will hold (e.g., `int`, `float`, `char`).
array_name: The name you give to the array.
rows: The number of rows in the array.
columns: The number of columns in the array.
Multidimensional Arrays
Multidimensional arrays extend the concept of two-dimensional arrays to more dimensions. They can be
visualized as arrays within arrays within arrays, and so on.
Syntax:
data_type array_name[d1][d2][d3]...[dn];
d1, d2, d3, ... dn represent the size of each dimension.
Example:
#include <stdio.h>
int main() {
int arr[2][3][4] = {
{ {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} },
{ {13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24} }
}; // 3D array initialization
return 0;
}
Expanation: `int arr[2][3][4]` declares a three-dimensional array named `arr` with 2 arrays, each containing 3
arrays, and each of those containing 4 elements. The elements are initialized in a nested manner.
Advantages of Multidimensional Arrays:
- They provide a convenient way to represent complex data structures.
- Useful in applications like 3D graphics, simulations, and scientific computations.
Viva Questions
How do you declare and initialize a two-dimensional array in C?
What is the difference between row-major and column-major order in memory
representation?
How can you pass a multi-dimensional array to a function in C?
What are the limitations or challenges of using multi-dimensional arrays in C?
Lecture 05:
Pointers in C
Pointers are a fundamental concept in C programming, providing powerful capabilities for dynamic memory
management, array manipulation, and efficient data handling.
Viva Questions
What is a pointer in C, and how is it different from a regular variable?
How do you declare, initialize, and use a pointer to access the value of a variable?
What is the significance of the * and & operators when working with pointers?
How does pointer arithmetic work, and what are its practical applications?
Lecture 06:
Accessing Value Through Pointer:
printf("Value of a: %d\n", *ptr); // Dereferencing ptr to get the value of a
`*ptr` accesses the value stored at the address `ptr` is pointing to.
The above code shows how a pointer variable (`ptr`) stores a pointer value (address of `a`) and allows access to the value
stored at that address through dereferencing.
Dangling Pointers
A dangling pointer is a pointer that points to a memory location that has been deallocated or freed. Accessing such
pointers leads to undefined behavior.
Example:
// Dynamically allocate memory
int *ptr = (int *)malloc(sizeof(int));
// Assign a value to the allocated memory
*ptr = 10;
// Print the value
printf("Value: %d\n", *ptr);
// Free the allocated memory
free(ptr);
// Undefined behavior To avoid using a dangling pointer,
// set it to NULL after freeing the memory
printf("Dangling pointer value: %d\n", *ptr);
Value: 10
Dangling pointer value: -1452514640
It is essential to initialize pointers either with a valid address or `NULL` to avoid undefined behavior.
NULL Pointer:
- A `NULL` pointer is a pointer that points to nothing.
- It is used to indicate that the pointer is not currently pointing to any valid memory location.
Example:
int *ptr = NULL; // Declares a NULL pointer
ptr = &a; // Initializes the pointer with the address of a
Viva Questions
How do you access and modify the value of a variable using its pointer in C?
What is the difference between dereferencing a pointer and referencing a variable?
What is a dangling pointer, and in what scenarios can it occur?
How can you avoid issues related to dangling pointers during program execution?
Lecture 07:
Arrays and Pointers
Arrays and pointers are closely related in C. The name of an array acts as a pointer to the first element of the array.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr now points to the first element of arr
printf("First element: %d\n", *ptr);
NOTE: In C, adding two pointers is not allowed and does not make sense. Pointers
represent memory addresses, so adding two memory addresses together doesn't
result in a meaningful address.
Viva Questions
How can an array name be used as a pointer, and what are the implications?
What is the relationship between *(arr + i) and arr[i] in C?
How does pointer arithmetic differ when applied to different data types (e.g., int* vs char*)?
How can pointers be used to dynamically manipulate arrays during runtime?
Lecture 08:
Structure Definition - Declaring Structures
A structure is a collection of variables under a single name, allowing you to combine variables of different types.
This is particularly useful for creating complex data types. To define a structure, you use the struct keyword
followed by the structure name and the body, which contains the structure members.
Example:
struct Person {
char name[50]; // Character array to store the name
int age; // Integer to store the age
float salary; // Floating-point number to store the salary
};
Once a structure is defined, you can declare variables of that structure type. Declaring a structure variable is like
declaring variables of built-in types.
Example:
struct Person person1, person2;
You can also declare and initialize the structure variable at the same time:
struct Person person1 = {"Alice", 30, 2500.5};
struct Person person2 = {"Bob", 25, 3000.75};
Giving Values to Members
You can assign values to structure members using the dot operator.
struct Person p1;
[Link] = 30;
[Link] = 2500.5;
strcpy([Link], "Alice");
Structure Initialization
Structures can be initialized at the time of declaration.
struct Person p2 = {"Bob", 25, 3000.75};
Accessing Structures
Structure members can be accessed using the dot operator.
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
printf("Salary: %.2f\n", [Link]);
Viva Questions
How do you define a structure in C, and what is the purpose of the struct keyword?
What is the difference between defining a structure and declaring a structure variable?
Can you declare a structure variable while defining the structure itself? Explain how.
How is memory allocated for structure members, and how does padding affect this?
Lecture 09:
Arrays of Structures
An array of structures allows you to store multiple records of the same structure type in a single array. This is
especially useful when you need to manage a collection of related data, like a list of employees, students, or any
other set of entities with similar attributes.
Defining an Array of Structures
To define an array of structures, you first declare the structure type and then create an array of that structure
type.
struct Person {
char name[50];
int age;
float salary;
};
Size of Structures
The `sizeof` operator is used to determine the size of a structure.
printf("Size of struct Person: %lu\n", sizeof(struct Person));
Lecture 10:
Structures within Structures - Nested Structures
A structure can also contain other structures as its members. This is useful for creating more complex data types
that represent entities with nested attributes. For example, an employee might have a nested address structure.
Nested Structures: Allow you to group complex attributes within a structure by nesting other structures.
struct Address {
char city[50];
char state[50];
};
struct Employee {
struct Address addr; // Nested structure
char name[50];
int age;
};
Both of these techniques help in organizing and managing related data more efficiently in C programs.
Accessing Nested Structures
You can access the members of the nested structure using the dot operator twice.
struct Employee emp1;
// Assign values to the nested structure
strcpy([Link], "New York");
strcpy([Link], "NY");
strcpy([Link], "Alice");
[Link] = 30;
Unions in C
A union is a user-defined data type similar to a structure, but with a key difference: **all members of a union
share the same memory location**. This means that a union can store only one of its members at a time. The
size of a union is equal to the size of its largest member.
Defining a Union
A union is defined using the `union` keyword, followed by the union name and the body containing the union
members.
union Data {
int i;
float f;
char str[20];
};
Advantages of Unions
Memory Efficiency: Unions are efficient in terms of memory usage since they use the same memory location for
all their members. This can be useful in scenarios where you need to work with different data types but only one
value at a time.
Practical Use Cases of Unions
Unions are often used in situations where you need to interpret the same data in different ways, such as:
-Embedded Systems: For interpreting the same data as different data types.
-Networking:For dealing with protocol headers where different fields may be interpreted as different data types.
-Variant Data Types:For storing different data types in a single variable, depending on the context.
`typedef` in C
`typedef` is a keyword in C that allows you to give a new name (alias) to an existing data type. This can help
make your code more readable and easier to manage, especially when dealing with complex data structures.
return 0;
}
`typedef struct { ... } Person;` defines a structure and creates an alias `Person` for that structure type. You can
now use `Person` directly to declare variables, without needing the `struct` keyword.
Viva Questions
What is a union in C, and how is it different from a structure?
How is memory allocated in a union, and how does that affect data storage?
Can you access multiple members of a union at the same time? Why or why not?
What are some practical use cases where unions are preferred over structures?
Sample programs
#include<stdio.h> #include<stdio.h>
int main(){ #define LEN 6
int temp,len=6; int main(){
int arr[6]={1,2,3,4,5,6}; int temp;
for(int i=0;i<len/2;i++){ int arr[LEN] = {1, 2, 3, 4, 5, 6};
temp = arr[i]; for(int i = 0; i < LEN / 2; i++){
arr[i]=arr[len-i-1]; temp = arr[i];
arr[len-i-1]=temp; arr[i] = arr[LEN - i - 1];
} arr[LEN - i - 1] = temp;
for(int i=0;i<len;i++){ }
printf("%d\t ",arr[i]); for(int i = 0; i < LEN; i++){
} printf("%d\t", arr[i]);
return 0; }
} return 0;
}
#include <stdio.h>
#include <math.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
double mean = sum / (double)n;
double sum_deviation = 0.0;
for (int i = 0; i < n; i++) {
sum_deviation += (arr[i] - mean) * (arr[i] - mean);
}
double standard_deviation = sqrt(sum_deviation / n);
printf("Mean = %.2f\n", mean);
printf("Standard Deviation = %.2f\n", standard_deviation);
return 0;
}
#include <stdio.h>
int main() {
int arr[] = {12, 11, 15, 10, 20};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\nMedian = %.2f\n", findMedian(arr, n));
return 0;
}
#include <stdio.h>
int main() {
int mat1[2][2] = {{1, 2}, {3, 4}};
int mat2[2][2] = {{5, 6}, {7, 8}};
int result[2][2] = {0};
// Multiplying matrices
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
// Display the result
printf("Resultant Matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0; }
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
int *ptr = arr;
for (int i = 0; i < n; i++) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum: %d\n", sum);
return 0;
}
Pointer positions
#include <stdio.h>
int Fact(int num){
if(num==0)
return(1);
else
return(num*Fact(num-1));
}
int main() {
int num;
printf("input a number");
scanf("%d",&num);
printf("factorial=%d",Fact(num));
return(0);
}
#include <stdio.h>
int main(){
int n,i,f;
f=i=1;
printf("Enter a Number to Find Factorial: ");
scanf("%d",&n);
while(i<=n){
f*=i;
i++;}
printf("The Factorial of %d is : %d",n,f);
return 0;
}
Employee structure to store the details of five employees
#include <stdio.h>
#include <stdlib.h>
typedef struct{
char name[30];
int id;
int salary;
} Employee;
int main(){
int i, n=5;
Employee employees[n];
//Taking each employee detail as input
printf("Enter %d Employee Details \n \n",n);
for(i=0; i<n; i++){
printf("Employee %d:- \n",i+1);
printf("Name: ");
scanf("%s",employees[i].name);
printf("Id: ");
scanf("%d",&employees[i].id);
printf("Salary: ");
scanf("%d",&employees[i].salary);
printf("\n");
}
//Displaying Employee details
printf("-------------- All Employees Details ---------
------\n");
for(i=0; i<n; i++){
printf("Name \t: ");
printf("%s \n",employees[i].name);
printf("Id \t: ");
printf("%d \n",employees[i].id);
printf("Salary \t: ");
printf("%d \n",employees[i].salary);
printf("\n");
}
return 0;
}
How to create and accesses 2D Arrays using Pointers
#include <stdio.h>
#include <stdlib.h>
int main() {
int **arr;
int rows, cols, i, j;
// Enter the number of rows and columns
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Dynamically allocate memory for the array of pointers to rows
arr = (int **)malloc(rows * sizeof(int *));
// Allocate memory for each row
for (i = 0; i < rows; i++) {
arr[i] = (int *)malloc(cols * sizeof(int));
}
// Initialize the array
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i][j] = (i + 1) * (j + 1); // Example initialization
}
}
// Print the array
printf("The elements of the 2D array are:\n");
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
// Free the dynamically allocated memory
for (i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
return 0;
}