0% found this document useful (0 votes)
5 views23 pages

Module 1

The document outlines the syllabus for BCS654A: Introduction to Data Structures, covering topics such as arrays, pointers, structures, and unions in C programming. It includes details on setting up VSCode for programming, along with examples and viva questions for each lecture. The course emphasizes fundamental concepts in data structures and programming techniques using C.

Uploaded by

sadwinisadwi145
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)
5 views23 pages

Module 1

The document outlines the syllabus for BCS654A: Introduction to Data Structures, covering topics such as arrays, pointers, structures, and unions in C programming. It includes details on setting up VSCode for programming, along with examples and viva questions for each lecture. The course emphasizes fundamental concepts in data structures and programming techniques using C.

Uploaded by

sadwinisadwi145
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

BCS654A: Introduction to Data Structures

(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.

Viva Questions on C Programming


What are the different storage classes in C and where are they used?
(e.g., auto, extern, static, register)
What is the difference between call by value and call by reference in C?
How does memory management work in C using malloc() and free()?
What is the difference between struct and union in C, and when would you use one over the
other?
Lecture 02:

VSCode Setup Guide for Newbies


Download & install VScode

Install Required Plugins


General Plugins Plugins For Programming:
Night Owl 1. C,C++: HTML:
Winter is Coming C/C++ IntelliSense, debug code-browsing. HTML CSS Support
Material Icon Theme C/C++ Compile Run Auto Rename Tag
Peacock 2. Python: Live Server
Prelitter Python (Microsoft) Live Preview
Guides Python Image Preview Microsoft Edge Tools
Rainbow Brackets 2 Python Test Explorer
Bracket Select Python IntelliSense CSS:
code runner Pylance SASS Formatter
tabnine Python Indent Live SASS Compiler
Path Intellisense Jupyter PostCSS Language Support
Peacock Jupyter Cell Tag Microsoft Edge Tools
Jupyter Key Map SCSS Formatter
Installations for VS Code Jupyter Notebook Renders (Microsoft) Tailwind Css IntelliSence
font victor-mono, Fira Code, IntelliCode Tailwind Docs
windows terminal, clink, oh my posh 3. Java:
Java Extension Pack
Installations for programming
4. PHP:
1, TDM GCC Compiler
2. Miniconda
3. JDK 5. Java Script
4. Xampp , Quokka
5. [Link] and ijsnorebook using npm

Setting up Terminal and Code Runner


Download and install and set the font family: font: victor-mono, Fira Code, NerdFonts, windows terminal, clink, oh my posh (select all and install the fonts)
Open settings(cnt+,) search for font -> and go to the below given option and set Ligatures: true, in the json file
"[Link]": "off",
"[Link]": "Dank Mono",
"[Link]": true,
"[Link]": true,

Set your default terminal application:


To open any command line application with Windows Terminal, set it as your default
terminal application.
1. Open Windows Terminal and go to the Settings UI window.
2. Select Startup and choose "Windows Terminal" as the Default
terminal application setting.

Set your default terminal application to be the VSCode Terminal


Press Ctrl + P type > and Type open user setting(json) into command palette and press
Enter
Code runner "[Link]" : true
OR
Go to File -> Preferences -> Settings; search "code-runner:Run In Terminal" Enable "Whether to run code in Integrated Terminal" option.

Style your Terminal (CMD)


Install Windows terminal from Microsoft store; Install Click ;
Copy the posh directory containing the .json themes in C:/users/
directory
Create a new file called [Link] in your Clink scripts directory( use clink info cmd to find the dir C:\Users\Ganesh V Bhat\AppData\Local\clink), and add the
below code to the file and save it,
load([Link]('oh-my-posh init cmd --config C:/Users/Posh/[Link]'):read("*a"))()

--load([Link]('oh-my-posh init cmd --config C:/Users/Posh/[Link]'):read("*a"))()


--load([Link]('oh-my-posh init cmd --config C:/Users/Posh/[Link]'):read("*a"))()

Use the terminal settings -> select the terminal and do necessary setting to further style your terminal like transparency:

Setting up VSCode to run C and C++ Files


. Download and install: TDM GCC Compiler
. Install the Plugins C/C++ IntelliSense, C/C++Compile & Run and Code Runner
. In the settings of the code runner options check the run in terminal options to activate taking inputs from the terminal
to run and F5 to debug
. Initially To debug click the debug icon to get the run and debug button in side bar ->
. Click the run and debug button and select the gcc compiler
. Click the create a launch Json file option
. Click Show all automatic debug configuration option
. Click Add Configuration button in the popup
select C++ (GDB) Attach
select C/C++ (GDB) Launch
file set the program path, externalConsole and miDebugger Path
"request": "launch",
"program": "${workspaceFolder}/${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"miDebuggerPath": "C:\\TDM-GCC-64\\bin\\[Link]",

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.

Initializing Two-Dimensional Arrays


Two-dimensional arrays can be initialized when they are declared. This allows you to assign values to each
element directly.
Example:
int matrix[2][2] = {{1, 2}, {3, 4}}; // 2x2 matrix initialization
- `int matrix[2][2]` declares a two-dimensional array named `matrix` with 2 rows and 2 columns.
- The elements are initialized as:
12
34
Example:
#include <stdio.h>
int main() {
// Declaring and initializing a 3x3 matrix
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// Looping through the array to print each element
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// Accessing and printing the element at row i and column j
printf("%d ", matrix[i][j]);
}
printf("\n"); // Newline for each row
}
return 0;
}
Expanation: `int matrix[3][3]` declares a two-dimensional array named `matrix` with 3 rows and 3 columns.
The elements are initialized using nested curly braces. The `for` loops iterate through each row and column,
printing the elements of the matrix.

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.

Pointer Declaration and Definition


Pointers are declared by specifying the data type followed by an asterisk (`*`) and the pointer name.
Syntax:
data_type *pointer_name;
Example:
int *ptr; // Declares a pointer to an integer
float *fptr; // Declares a pointer to a float

Pointer Constants, Pointer Values, and Pointer Variables


Pointer Constants:
- The actual memory address stored in a pointer.
- Example: `&a;` (address of variable `a`).
Pointer Values:
- The memory addresses that pointers hold.
- Example: `int *ptr = &a;` (pointer `ptr` holds the address of `a`).
Pointer Variables:
- Variables that store the address of another variable.
- Example: `int *ptr;` (declares a pointer variable `ptr`).
Example:
int a = 10;
int *ptr = &a; // ptr is a pointer variable holding the address of a
- `a` is an integer variable initialized to 10.
- `ptr` is a pointer variable holding the address of `a`.

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.

Accessing Variables Through Pointers


You can access and modify the value of a variable through its pointer using the dereferencing operator (`*`).
Example:
int a = 10;
int *ptr = &a;
printf("Value of a: %d\n", *ptr); // Accessing value of a through ptr
*ptr = 20; // Modifying value of a through ptr
printf("New value of a: %d\n", *ptr);

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);

Pointer Arithmetic and Arrays


Pointer arithmetic operations allow you to navigate through an array efficiently. Here are the key operations:
Incrementing a Pointer
- Moves the pointer to the next element of the array.
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Points to the first element
ptr++; // Now points to the second element
Decrementing a Pointer
- Moves the pointer to the previous element of the array.
int *ptr = &arr[4]; // Points to the last element
ptr--; // Now points to the second-last element
Adding an Integer to a Pointer
- Moves the pointer forward by the specified number of elements.
int *ptr = arr;
ptr += 2; // Now points to the third element
Subtracting an Integer from a Pointer
- Moves the pointer backward by the specified number of elements.
int *ptr = &arr[4];
ptr -= 3; // Now points to the second element
Subtracting Two Pointers
- Calculates the number of elements between two pointers.
int *ptr1 = &arr[1];
int *ptr2 = &arr[4];
int distance = ptr2 - ptr1; // Distance is 3 elements
Comparing Two Pointers
- Compares the positions of two pointers to determine their relative locations in memory.
int *ptr1 = &arr[2];
int *ptr2 = &arr[4];
if (ptr1 < ptr2) {
printf("ptr1 points to an earlier position than ptr2\n");
}
These operations allow you to traverse and manipulate arrays efficiently using pointers. They are especially useful for
dynamic memory management and accessing elements in a flexible way.

Pointers and One-Dimensional Arrays


Pointers can be used to iterate through one-dimensional arrays and perform operations on them.
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // Displaying array elements using pointer
}

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]);

Comparison of Structure Variables


Comparing structure variables directly isn't allowed in C. You need to compare each member separately.
if ([Link] == [Link] && strcmp([Link], [Link]) == 0 && [Link] == [Link]) {
printf("Structures are equal\n");
}

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;
};

struct Person people[2] = {


{"Alice", 30, 2500.5},
{"Bob", 25, 3000.75}
};

Accessing Array Elements


Each element of the array is a structure variable, and you can access the members of these structures using the
dot operator and array indexing.
// Access the first person's details
printf("Person 1: %s, Age: %d, Salary: %.2f\n", people[0].name, people[0].age,
people[0].salary);
// Access the second person's details
printf("Person 2: %s, Age: %d, Salary: %.2f\n", people[1].name, people[1].age,
people[1].salary);

Modifying Array Elements


You can also modify the members of structures within the array just like any other structure variable.
// Update the age of the first person
people[0].age = 31;
// Update the salary of the second person
people[1].salary = 3200.75;

Iterating Through an Array of Structures


You can use loops to iterate through an array of structures, making it easy to perform operations on each
element.
for (int i = 0; i < 2; i++) {
printf("Person %d: %s, Age: %d, Salary: %.2f\n", i+1, people[i].name, people[i].age,
people[i].salary);
}
Arrays of structures in C provide a powerful way to handle collections of related data. They allow you to group
multiple records together and perform operations on them efficiently. Whether you're working with a list of
employees, students, or any other set of entities, arrays of structures help keep your data organized and
manageable.

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));

Arrays within Structures


A structure can contain arrays as its members. This allows you to group related data items of the same type
within the structure. It's particularly useful for representing entities that have a fixed number of similar
attributes, like a student's marks in different subjects.
struct Student {
char name[50]; // Character array to store the student's name
int marks[5]; // Integer array to store marks in 5 subjects
};
Accessing Arrays within Structures
You can access and modify the elements of the array within the structure using the dot operator and array
indexing.
Arrays within Structures: Allow you to group related data items of the same type within a structure.
struct Student student1;
strcpy([Link], "John");

// Assign marks to the student


[Link][0] = 85;
[Link][1] = 90;
[Link][2] = 78;
[Link][3] = 88;
[Link][4] = 92;

// Access the marks


for (int i = 0; i < 5; i++) {
printf("Mark %d: %d\n", i+1, [Link][i]);
}
Viva Questions
How do you declare and initialize an array of structures in C?
What are the advantages of using an array of structures when managing related data sets?
How can you access and modify elements of an array declared inside a structure?
What is the difference in memory layout between an array of structures and a structure
containing an array?

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;

// Access the values of the nested structure


printf("Employee Name: %s\n", [Link]);
printf("Employee Age: %d\n", [Link]);
printf("City: %s\n", [Link]);
printf("State: %s\n", [Link]);

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];
};

Declaring Union Variables


You can declare union variables in the same way as structure variables.
union Data d1, d2;

Storing Values in Union Members


Since all members of a union share the same memory, assigning a value to one member will overwrite the value
of other members. Let's see how this works in practice:
// Assign an integer value
d1.i = 10;
printf("d1.i: %d\n", d1.i);

// Assign a float value (overwrites the integer value)


d1.f = 220.5;
printf("d1.f: %.2f\n", d1.f);

// Assign a string value (overwrites the float value)


strcpy([Link], "Hello");
printf("[Link]: %s\n", [Link]);

In the above example:


- When you assign `10` to `d1.i`, the integer value is stored.
- When you assign `220.5` to `d1.f`, the previous integer value is overwritten by the float value.
- When you copy the string `"Hello"` into `[Link]`, the previous float value is overwritten by the string.

Accessing Union Members


You can access union members using the dot operator, similar to structures.
union Data d;
// Assign values
d.i = 100;
printf("Integer: %d\n", d.i);
d.f = 123.45;
printf("Float: %.2f\n", d.f);
strcpy([Link], "C Programming");
printf("String: %s\n", [Link]);

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.

Using `typedef` with Structures


When you define a structure, you often use the `struct` keyword each time you declare a variable of that
structure type. `typedef` can simplify this by allowing you to create an alias for the structure.
#include <stdio.h>
#include <string.h>
// Define a structure
typedef struct {
char name[50];
int age;
} Person;
// Declare a variable of type Person
Person p3;
int main() {
// Assign values to the structure members
strcpy([Link], "Charlie");
[Link] = 28;

// Access and print the structure members


printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);

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.

Benefits of Using `typedef`


Readability: Simplifies the declaration of variables, making the code easier to read and write.
-Abstraction:Helps in creating more understandable code by providing meaningful names for data types.
-Maintainability: Makes it easier to change the underlying data type if needed, without modifying the entire
codebase.

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

WRITE A C CODE TO REVERSE AN ARRAY

#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;
}

FIND THE MISSING ELEMENT


#include <stdio.h>
int main() {
int arr[] = {1, 2, 4, 5, 6}; // Initialize the array with the missing element
int size = sizeof(arr) / sizeof(arr[0]);
int total = (size + 1) * (size + 2) / 2; // Sum of the first n natural numbers
for (int i = 0; i < size; i++) {
total -= arr[i];
}
int missingElement = total;
printf("The missing element is: %d\n", missingElement);
return 0;
}

FIND THE MEAN & STD-DEVEATION OF AN ARRAY

#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;
}

WRITE A C CODE TO PRINT THE PASCALS TRIANGLR


#include <stdio.h>
int main() {
int n = 5;
int arr[n][n];
for (int line = 0; line < n; line++) {
for (int i = 0; i <= line; i++) {
if (line == i || i == 0) {
arr[line][i] = 1;
} else {
arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
}
printf("%d ", arr[line][i]);
}
printf("\n");
}
return 0; }

SORT A ARRAY AND FIND ITS MEDIAN

#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;
}

void sort(int arr[], int n) {


for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}

double findMedian(int arr[], int n) {


if (n % 2 == 0) {
return (arr[n/2 - 1] + arr[n/2]) / 2.0;
} else {
return arr[n/2];
}
}
Multiply two matrices

#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; }

FIND LARGEST OF N NUMBERS USING POINTERS


#include <stdio.h>
int main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
int *ptr = arr;
for (i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
int largest = *ptr;
for (i = 1; i < n; i++) {
if (*(ptr + i) > largest) {
largest = *(ptr + i);
}
}
printf("Largest number: %d\n", largest);
return 0;
}

FIND THE SUM OF N NUMBERS USING POINTERS

#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

Subtract an integer from a pointer to move it backward by that number of elements


and compar two pointers to check their relative positions in memory
#include <stdio.h>
int main() {
// Part 1: Navigating through an array using pointers
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[4]; // Points to the last element
ptr -= 2; // Points to the third element
printf("Third element: %d\n", *ptr);
// Part 2: Comparing two pointers to check their relative positions in memory
int *ptr1 = &arr[2]; // Points to the third element
int *ptr2 = &arr[4]; // Points to the fifth element

if (ptr1 < ptr2) {


printf("ptr1 points to an earlier position than ptr2\n");
} else {
printf("ptr1 does not point to an earlier position than ptr2\n");
}
return 0;
}

Factorial of a number using A) While loop , B) Recursive function

#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;
}

You might also like