Programming in C Unit-III BCA Semester I
1
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Unit-III: Arrays, Structures and Unions
Introduction
• In C programming, data handling requires grouping related elements and managing
collections of values.
• arrays, structures, and unions, which provide systematic ways to organise and manage data.
• These concepts are essential for writing efficient, structured, and memory-optimized C
programs, useful in handling tasks like record management and matrix operations.
I)Arrays
Introduction to Arrays
• When handling many similar data values, using separate variables increases complexity.
• To simplify this, C provides arrays, which allow storing multiple values of the same data
type in a single variable.
• Arrays enable efficient storage and easy access using an index, making them ideal for
storing items like student marks or employee salaries.
Programming in C Unit-III BCA Semester I
2
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Definition of an Array
• An array is a finite, ordered, homogeneous collection of elements stored in contiguous
memory locations, accessed using a common name and an index.
• It is a linear static data structure, meaning its size is fixed during declaration.
Examples of Arrays
1.Integer Array
int numArray[12] = {11, 9, 17, 89, 1, 90, 19, 5, 3, 23, 43, 99};
2. Float Array
float marks[5] = {88.5, 76.0, 92.3, 69.5, 80.0};
3.Character Array (String)
char subject[8] = "Computer";
Characteristics of Arrays
1. Arrays store multiple elements of the same data type.
2. All elements are placed in contiguous (continuous) memory locations.
3. Each element is accessed using an index, with C following 0-based indexing.
4. The size of an array is fixed at the time of declaration and cannot be changed later.
5. Arrays provide fast and direct access to elements through indexing.
Need for Arrays
1. Arrays store many values of the same data type efficiently.
2. They remove the need to declare multiple separate variables.
3. Arrays provide quick access to elements using indices.
4. They make programs simpler and easier to manage.
5. Arrays help in systematic processing of large data sets.
Programming in C Unit-III BCA Semester I
3
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Operations on an Array
1. Traversing: Accessing and processing each element of the array sequentially.
2. Searching: Finding whether a particular element exists in the array.
3. Sorting: Arranging array elements in a specific order (ascending or descending).
4. Inserting: Adding a new element at a specified position in the array.
5. Deleting: Removing an element from a specified position in the array.
Applications of Arrays
1. Used for storing and processing lists of data such as marks, salaries, or ages.
2. Helpful in representing mathematical vectors, matrices, and tables.
3. Widely used in searching and sorting algorithms.
4. Form the basis for data structures like stacks, queues, and graphs.
Advantages of Arrays
1. Code optimisation: Arrays allow accessing data with fewer lines of code.
2. Easy traversal: Elements can be easily processed using loops.
3. Easy sorting: Sorting operations can be performed with simple code.
4. Random access: Any element can be accessed directly using its index.
5. Supports data structures: Arrays make it easy to implement structures like stacks and
queues.
6. Improves readability: Programs become more organised and easier to understand.
Disadvantages of Arrays
1. Fixed size: The array size cannot be changed during program execution.
2. Costly insertion/deletion: Adding or removing elements requires shifting, which is time-
consuming.
3. Memory wastage: Unused allocated space leads to memory loss.
4. Homogeneous data only: Arrays can store only one data type at a time
Programming in C Unit-III BCA Semester I
4
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Classification of Arrays
In C programming, arrays are classified mainly based on their dimensionality. There are two types
of arrays:
I) One Dimensional arrays (1-D arrays)
Definition
A one-dimensional array is a collection of elements of the same data type arranged in a single
row (linear form) and stored in contiguous memory locations.
a)1-D Array Declaration in C
• To declare an array in C, we use square brackets [] after the array name.
• The size of the array (number of elements) is written inside the brackets.
Syntax:
data_type array_name[size];
➢ data_type → type of elements (int, float, char, etc.)
➢ array_name → name of the array
➢ size → number of elements
Examples:
int numbers[10]; // array of 10 integers
float marks[5]; // array of 5 floats
char name[20]; // array of 20 characters (strings)
Programming in C Unit-III BCA Semester I
5
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
b) Types of 1-D Array Initialization in C
1. Compile-time (static)Initialization
Values are assigned at the time of declaration.
int marks[5] = {90, 85, 78, 92, 88};
2. Partial Initialization
Only some values are given; the remaining are set to 0.
int numbers[5] = {1, 2}; // stores 1, 2, 0, 0, 0
3. Implicit Size Initialization
The size is automatically determined by the number of elements.
int nums[] = {10, 20, 30, 40};
4. Runtime (Dynamic) Initialization
Values are entered by the user or assigned during program execution.
int arr[5];
for(int i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
c) Accessing Elements of a 1-D Array
Use the index (starting from 0) to read an element:
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50}; // Compile-time initialization
// Access elements
printf("First element: %dn", arr[0]); //10
printf("Third element: %dn", arr[2]); //30
return 0;
}
Programming in C Unit-III BCA Semester I
6
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
d) Updating Elements of a 1-D Array
Assign a new value to an element using its index:
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
// Update elements
arr[1] = 25; // Update second element
arr[4] = 55; // Update fifth element
// Display updated array
printf("nUpdated Array Elements:n");
for(int i = 0; i < 5; i++)
{
printf("arr[%d] = %dn", i, arr[i]);
}
return 0;
}
e) Memory Representation of 1-D Array
• In C, the elements of an array are stored in continuous memory locations.
• Each element is accessed using an index, which starts from 0.
• The base address refers to the memory location of the first element.
• The address of the i-th element is calculated as:
Address of element = Base address + (i × size of each element)
Example:
• If int marks[5] = {90, 97, 95, 99, 100}; is stored at base address 3020 and each integer
takes 2 bytes (depends on system), memory allocation will be:
Programming in C Unit-III BCA Semester I
7
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
II) Multidimensional Arrays
• In C, arrays store multiple values of the same data type.
• Multidimensional arrays represent data in tables, grids, or matrices (e.g., student marks,
chessboard, image pixels).
• A multidimensional array is an array of arrays, created with more than one dimension.
• Common types include 2-D, 3-D, and higher-dimensional arrays, with 2-D arrays being the
most common (rows and columns).
Syntax for declaration:
data_type array_name[size1][size2]........[sizeN];
Examples:
int matrix[3][3]; // 2-D array (3 rows, 3 columns)
int cube[3][3][3]; // 3-D array (like a cube of data)
Two-Dimensional (2-D) Arrays
Definition
A two-dimensional (2-D) array is a collection of elements arranged in rows and columns,
where each element is accessed using two indices.
• It is used to store data in the form of a table or matrix with rows and columns.
Programming in C Unit-III BCA Semester I
8
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
a) Declaration of 2-D Arrays
To declare a 2-D array, we use two sets of square brackets [ ] [ ]:
Syntax:
data_type array_name[rows][columns];
• data_type → type of elements (int, float, char, etc.)
• array_name → name of the array
• rows, columns → size (number of rows and columns)
Example:
int matrix[3][3]; // 3x3 integer matrix, this can store 3 × 3 = 09 elements.
float marks[2][5]; // 2 rows and 5 columns of floats, this can store 2 × 5 = 10 elements.
char name[4][20]; // 4 strings, each of max length 20, his can store 4 × 20 = 80 elements.
b) Types of 2-D Array Initialization
1. Compile-time Initialization
Values assigned during declaration.
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
2. Partial Initialization
Remaining elements are set to 0.
int mat[2][3] = { {1, 2}, {4} }; // stores: {1,2,0} and {4,0,0}
3. Implicit Row Size Initialization
Number of rows can be left empty (columns must be given).
int mat[][3] = { {1, 2, 3}, {4, 5, 6} };
Programming in C Unit-III BCA Semester I
9
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
4. Runtime (Dynamic) Initialization
Values entered by user at runtime.
int mat[2][3];
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
{
scanf("%d", &mat[i][j]);
}
}
c) Accessing Elements of a 2-D Array
Use row index and column index.
#include <stdio.h>
int main()
{
int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };
printf("Element at [0][1] = %dn", mat[0][1]); // 20
printf("Element at [1][2] = %dn", mat[1][2]); // 60
return 0;
}
Programming in C Unit-III BCA Semester I
10
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
d) Updating Elements of a 2-D Array
Assign new values using row and column index.
#include <stdio.h>
int main()
{
int mat[2][3] = { {10, 20, 30}, {40, 50, 60} };
// Update elements
mat[0][1] = 25; // Update row 0, col 1
mat[1][2] = 65; // Update row 1, col 2
// Display updated matrix
printf("nUpdated Matrix:n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 3; j++)
{
printf("%d ", mat[i][j]);
}
printf("n");
}
return 0;
}
Programming in C Unit-III BCA Semester I
11
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
e) Memory representation of 2-D Array
int arr[3][3] = { {24, 15, 34}, {26, 134, 194}, {67, 23, 345} } is stored in memory as
Here, the base address is the address of the 2-D array or the address of the first object stored in the
2-D array. The memory address increases by 4 bytes (the size of the int data type).
II) Structures
Introduction:
• A structure in C is a user-defined data type that groups variables of different types under
a single name.
• It is useful for representing real-world entities, such as student details or textbook
information.
Definition:
A structure is a collection of heterogeneous variables under a single name, enabling logical
representation of real-world entities and improving program organisation.
Syntax:
• A structure is defined using the keyword struct.
• The items in the structure are called its members and they can be of any valid data type.
struct StructureName
{
data_type member1;
data_type member2;
...
data_type memberN;
};
Programming in C Unit-III BCA Semester I
12
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example:1
Memory Size of a Structure:
• The total memory size of a structure is the sum of the sizes of its members plus any
padding added by the compiler for alignment.
Example:2
struct textbook
{
char name[40];
char author[20];
int pages;
};
Programming in C Unit-III BCA Semester I
13
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Applications of Structures
1. Representing real-world entities like students, employees, books, or patients with
multiple attributes.
2. Managing records in databases or file systems.
3. Creating arrays of structures for handling collections of related data.
4. Implementing complex data structures like linked lists, stacks, and queues.
5. Organising data for file handling and data exchange between functions.
Need for Structures/ Advantages of Structures
1. To group different data types into a single unit.
2. To model real-world entities like students, employees, or books with multiple attributes.
3. To improve program readability and logical organisation of data.
4. To reduce program complexity and enhance reusability.
5. To serve as a foundation for advanced concepts like arrays of structures, pointers to
structures, and file handling.
Disadvantages of Structures
1. Cannot directly perform arithmetic or operations on entire structures.
2. Memory allocation is fixed and may lead to wastage if not used efficiently.
3. Accessing individual members requires explicit member names.
4. Structures cannot contain operations (functions) directly like objects in OOP.
5. Handling very large structures can increase program complexity and execution time.
Programming in C Unit-III BCA Semester I
14
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Declaring Structure Variables
Structure variables can be declared in two ways:
1)Method 1 – After structure definition:
struct Student
{
int rollno;
char name[20];
float marks;
};
struct Student s1, s2; // declaring variables
2)Method 2 – Along with structure definition:
struct Student
{
int rollno;
char name[20];
float marks;
} s1, s2;
Initializing Structure Members
1) Initialize a structure at the time of declaration:
#include <stdio.h>
// Define the structure
struct Student
{
int rollno;
char name[20];
float marks;
};
Programming in C Unit-III BCA Semester I
15
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
int main()
{
// Declare and initialize structure variables
struct Student s1 = {101, "Arun", 85.5};
struct Student s2 = {102, "Riya", 92.0};
// Display values of s1
printf("Student 1 Details:n");
printf("Roll Number: %dn", s1.rollno);
printf("Name: %sn", s1.name);
printf("Marks: %.2fnn", s1.marks);
// Display values of s2
printf("Student 2 Details:n");
printf("Roll Number: %dn", s2.rollno);
printf("Name: %sn", s2.name);
printf("Marks: %.2fn", s2.marks);
return 0;
}
2) assign values later:
s1.rollno = 102;
strcpy(s1.name, "Meena"); // for strings use strcpy()
s1.marks = 90.0;
Accessing Structure Members
Members are accessed using the dot operator (.)
Programming in C Unit-III BCA Semester I
16
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
III) Unions
Introduction:
• A union in C is a user-defined data type similar to a structure, but all members share
the same memory location.
• Only one member can hold a value at a time.
Definition:
A union is a C data type where all members share the same memory location, allowing only one
active value at a time.
Memory Allocation:
• The memory allocated for a union equals the size of its largest member.
• Assigning a value to one member overwrites the previous value stored in the union
Applications of Unions
1. Save memory in programs with limited resources.
2. Share memory in embedded systems and device drivers.
3. Use the same data in different ways, like bit fields or packets.
4. Access the same memory as different data types (type punning).
5. Help in designing compilers and operating systems efficiently.
Advantages/Need of Unions in C
1. Efficient memory usage, as all members share the same memory.
2. Handle different data types at different times using the same memory.
3. Useful in embedded systems and low-level programming where memory is limited.
4. Facilitates type conversion, e.g., accessing the same data as integer or float.
5. Optimized storage when only one value is needed at a time.
Programming in C Unit-III BCA Semester I
17
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Disadvantages of Unions
1. Only one member can hold a value at a time.
2. Assigning a value to one member overwrites the previous value.
3. Cannot store multiple values simultaneously.
4. Accessing the wrong member may lead to unexpected results.
5. Not suitable when multiple data elements need to be stored concurrently.
Declaration of Union
Unions are declared using the keyword union.
Syntax:
union UnionName
{
data_type member1;
data_type member2;
...
data_type memberN;
};
Initialization of Union
1)Method 1 – At the time of declaration:
#include <stdio.h>
// Define the union
union Data
{
int i;
float f;
char str[20];
};
Programming in C Unit-III BCA Semester I
18
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
int main()
{
// Method 1: Initialize at the time of declaration
union Data d1 = {10}; // Initializes the first member 'i'
// Access and display the value
printf("Value of i: %dn", d1.i);
return 0;
}
2) Method 2 – Assigning later:
int main()
{
// Declare a union variable
union Data d2;
// Assign integer value
d2.i = 10;
printf("After assigning integer:ni = %dnn", d2.i);
// Assign float value
d2.f = 5.5;
printf("After assigning float:nf = %.2fnn", d2.f);
// Assign string value
strcpy(d2.str, "BCA");
printf("After assigning string:nstr = %sn", d2.str);
return 0;
}
Programming in C Unit-III BCA Semester I
19
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Comparison of Arrays, Structures, and Unions in C
Arrays Structures Unions
1. Store multiple values of
the same data type.
1. Can store multiple
variables of different data
types.
1. Can store multiple variables of
different types, but only one value
at a time.
2. Size is fixed at the time
of declaration.
2. Size depends on all
members combined.
2. Size is equal to the largest
member.
3. Elements are accessed
using indices.
3. Members are accessed
using the dot (.) operator.
3. Members are accessed using
the dot (.) operator.
4. All elements occupy
separate memory locations.
4. Each member has its
own memory location.
4. All members share the same
memory location.
5. Used for storing lists,
matrices, or sequences of
similar data.
5. Used to represent real-
world entities logically.
5. Used for memory-efficient
storage where only one value is
needed at a time.
6. Supports traversal,
searching, and sorting
operations.
6. Can be nested or
combined with arrays and
pointers.
6. Efficient in low-memory
applications like embedded
systems.
7. Applications: storing
student marks, employee
salaries, matrices.
Applications: storing
student records, book
details, employee profiles.
Applications: type punning,
sharing memory in embedded
systems, interpreting data in
multiple formats.
*** *** ***

Programming in C: Unit-III: Arrays, Structures and Unions

  • 1.
    Programming in CUnit-III BCA Semester I 1 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Unit-III: Arrays, Structures and Unions Introduction • In C programming, data handling requires grouping related elements and managing collections of values. • arrays, structures, and unions, which provide systematic ways to organise and manage data. • These concepts are essential for writing efficient, structured, and memory-optimized C programs, useful in handling tasks like record management and matrix operations. I)Arrays Introduction to Arrays • When handling many similar data values, using separate variables increases complexity. • To simplify this, C provides arrays, which allow storing multiple values of the same data type in a single variable. • Arrays enable efficient storage and easy access using an index, making them ideal for storing items like student marks or employee salaries.
  • 2.
    Programming in CUnit-III BCA Semester I 2 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Definition of an Array • An array is a finite, ordered, homogeneous collection of elements stored in contiguous memory locations, accessed using a common name and an index. • It is a linear static data structure, meaning its size is fixed during declaration. Examples of Arrays 1.Integer Array int numArray[12] = {11, 9, 17, 89, 1, 90, 19, 5, 3, 23, 43, 99}; 2. Float Array float marks[5] = {88.5, 76.0, 92.3, 69.5, 80.0}; 3.Character Array (String) char subject[8] = "Computer"; Characteristics of Arrays 1. Arrays store multiple elements of the same data type. 2. All elements are placed in contiguous (continuous) memory locations. 3. Each element is accessed using an index, with C following 0-based indexing. 4. The size of an array is fixed at the time of declaration and cannot be changed later. 5. Arrays provide fast and direct access to elements through indexing. Need for Arrays 1. Arrays store many values of the same data type efficiently. 2. They remove the need to declare multiple separate variables. 3. Arrays provide quick access to elements using indices. 4. They make programs simpler and easier to manage. 5. Arrays help in systematic processing of large data sets.
  • 3.
    Programming in CUnit-III BCA Semester I 3 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Operations on an Array 1. Traversing: Accessing and processing each element of the array sequentially. 2. Searching: Finding whether a particular element exists in the array. 3. Sorting: Arranging array elements in a specific order (ascending or descending). 4. Inserting: Adding a new element at a specified position in the array. 5. Deleting: Removing an element from a specified position in the array. Applications of Arrays 1. Used for storing and processing lists of data such as marks, salaries, or ages. 2. Helpful in representing mathematical vectors, matrices, and tables. 3. Widely used in searching and sorting algorithms. 4. Form the basis for data structures like stacks, queues, and graphs. Advantages of Arrays 1. Code optimisation: Arrays allow accessing data with fewer lines of code. 2. Easy traversal: Elements can be easily processed using loops. 3. Easy sorting: Sorting operations can be performed with simple code. 4. Random access: Any element can be accessed directly using its index. 5. Supports data structures: Arrays make it easy to implement structures like stacks and queues. 6. Improves readability: Programs become more organised and easier to understand. Disadvantages of Arrays 1. Fixed size: The array size cannot be changed during program execution. 2. Costly insertion/deletion: Adding or removing elements requires shifting, which is time- consuming. 3. Memory wastage: Unused allocated space leads to memory loss. 4. Homogeneous data only: Arrays can store only one data type at a time
  • 4.
    Programming in CUnit-III BCA Semester I 4 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Classification of Arrays In C programming, arrays are classified mainly based on their dimensionality. There are two types of arrays: I) One Dimensional arrays (1-D arrays) Definition A one-dimensional array is a collection of elements of the same data type arranged in a single row (linear form) and stored in contiguous memory locations. a)1-D Array Declaration in C • To declare an array in C, we use square brackets [] after the array name. • The size of the array (number of elements) is written inside the brackets. Syntax: data_type array_name[size]; ➢ data_type → type of elements (int, float, char, etc.) ➢ array_name → name of the array ➢ size → number of elements Examples: int numbers[10]; // array of 10 integers float marks[5]; // array of 5 floats char name[20]; // array of 20 characters (strings)
  • 5.
    Programming in CUnit-III BCA Semester I 5 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca b) Types of 1-D Array Initialization in C 1. Compile-time (static)Initialization Values are assigned at the time of declaration. int marks[5] = {90, 85, 78, 92, 88}; 2. Partial Initialization Only some values are given; the remaining are set to 0. int numbers[5] = {1, 2}; // stores 1, 2, 0, 0, 0 3. Implicit Size Initialization The size is automatically determined by the number of elements. int nums[] = {10, 20, 30, 40}; 4. Runtime (Dynamic) Initialization Values are entered by the user or assigned during program execution. int arr[5]; for(int i = 0; i < 5; i++) { scanf("%d", &arr[i]); } c) Accessing Elements of a 1-D Array Use the index (starting from 0) to read an element: #include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; // Compile-time initialization // Access elements printf("First element: %dn", arr[0]); //10 printf("Third element: %dn", arr[2]); //30 return 0; }
  • 6.
    Programming in CUnit-III BCA Semester I 6 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca d) Updating Elements of a 1-D Array Assign a new value to an element using its index: #include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; // Update elements arr[1] = 25; // Update second element arr[4] = 55; // Update fifth element // Display updated array printf("nUpdated Array Elements:n"); for(int i = 0; i < 5; i++) { printf("arr[%d] = %dn", i, arr[i]); } return 0; } e) Memory Representation of 1-D Array • In C, the elements of an array are stored in continuous memory locations. • Each element is accessed using an index, which starts from 0. • The base address refers to the memory location of the first element. • The address of the i-th element is calculated as: Address of element = Base address + (i × size of each element) Example: • If int marks[5] = {90, 97, 95, 99, 100}; is stored at base address 3020 and each integer takes 2 bytes (depends on system), memory allocation will be:
  • 7.
    Programming in CUnit-III BCA Semester I 7 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca II) Multidimensional Arrays • In C, arrays store multiple values of the same data type. • Multidimensional arrays represent data in tables, grids, or matrices (e.g., student marks, chessboard, image pixels). • A multidimensional array is an array of arrays, created with more than one dimension. • Common types include 2-D, 3-D, and higher-dimensional arrays, with 2-D arrays being the most common (rows and columns). Syntax for declaration: data_type array_name[size1][size2]........[sizeN]; Examples: int matrix[3][3]; // 2-D array (3 rows, 3 columns) int cube[3][3][3]; // 3-D array (like a cube of data) Two-Dimensional (2-D) Arrays Definition A two-dimensional (2-D) array is a collection of elements arranged in rows and columns, where each element is accessed using two indices. • It is used to store data in the form of a table or matrix with rows and columns.
  • 8.
    Programming in CUnit-III BCA Semester I 8 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca a) Declaration of 2-D Arrays To declare a 2-D array, we use two sets of square brackets [ ] [ ]: Syntax: data_type array_name[rows][columns]; • data_type → type of elements (int, float, char, etc.) • array_name → name of the array • rows, columns → size (number of rows and columns) Example: int matrix[3][3]; // 3x3 integer matrix, this can store 3 × 3 = 09 elements. float marks[2][5]; // 2 rows and 5 columns of floats, this can store 2 × 5 = 10 elements. char name[4][20]; // 4 strings, each of max length 20, his can store 4 × 20 = 80 elements. b) Types of 2-D Array Initialization 1. Compile-time Initialization Values assigned during declaration. int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} }; 2. Partial Initialization Remaining elements are set to 0. int mat[2][3] = { {1, 2}, {4} }; // stores: {1,2,0} and {4,0,0} 3. Implicit Row Size Initialization Number of rows can be left empty (columns must be given). int mat[][3] = { {1, 2, 3}, {4, 5, 6} };
  • 9.
    Programming in CUnit-III BCA Semester I 9 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 4. Runtime (Dynamic) Initialization Values entered by user at runtime. int mat[2][3]; for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { scanf("%d", &mat[i][j]); } } c) Accessing Elements of a 2-D Array Use row index and column index. #include <stdio.h> int main() { int mat[2][3] = { {10, 20, 30}, {40, 50, 60} }; printf("Element at [0][1] = %dn", mat[0][1]); // 20 printf("Element at [1][2] = %dn", mat[1][2]); // 60 return 0; }
  • 10.
    Programming in CUnit-III BCA Semester I 10 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca d) Updating Elements of a 2-D Array Assign new values using row and column index. #include <stdio.h> int main() { int mat[2][3] = { {10, 20, 30}, {40, 50, 60} }; // Update elements mat[0][1] = 25; // Update row 0, col 1 mat[1][2] = 65; // Update row 1, col 2 // Display updated matrix printf("nUpdated Matrix:n"); for(int i = 0; i < 2; i++) { for(int j = 0; j < 3; j++) { printf("%d ", mat[i][j]); } printf("n"); } return 0; }
  • 11.
    Programming in CUnit-III BCA Semester I 11 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca e) Memory representation of 2-D Array int arr[3][3] = { {24, 15, 34}, {26, 134, 194}, {67, 23, 345} } is stored in memory as Here, the base address is the address of the 2-D array or the address of the first object stored in the 2-D array. The memory address increases by 4 bytes (the size of the int data type). II) Structures Introduction: • A structure in C is a user-defined data type that groups variables of different types under a single name. • It is useful for representing real-world entities, such as student details or textbook information. Definition: A structure is a collection of heterogeneous variables under a single name, enabling logical representation of real-world entities and improving program organisation. Syntax: • A structure is defined using the keyword struct. • The items in the structure are called its members and they can be of any valid data type. struct StructureName { data_type member1; data_type member2; ... data_type memberN; };
  • 12.
    Programming in CUnit-III BCA Semester I 12 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example:1 Memory Size of a Structure: • The total memory size of a structure is the sum of the sizes of its members plus any padding added by the compiler for alignment. Example:2 struct textbook { char name[40]; char author[20]; int pages; };
  • 13.
    Programming in CUnit-III BCA Semester I 13 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Applications of Structures 1. Representing real-world entities like students, employees, books, or patients with multiple attributes. 2. Managing records in databases or file systems. 3. Creating arrays of structures for handling collections of related data. 4. Implementing complex data structures like linked lists, stacks, and queues. 5. Organising data for file handling and data exchange between functions. Need for Structures/ Advantages of Structures 1. To group different data types into a single unit. 2. To model real-world entities like students, employees, or books with multiple attributes. 3. To improve program readability and logical organisation of data. 4. To reduce program complexity and enhance reusability. 5. To serve as a foundation for advanced concepts like arrays of structures, pointers to structures, and file handling. Disadvantages of Structures 1. Cannot directly perform arithmetic or operations on entire structures. 2. Memory allocation is fixed and may lead to wastage if not used efficiently. 3. Accessing individual members requires explicit member names. 4. Structures cannot contain operations (functions) directly like objects in OOP. 5. Handling very large structures can increase program complexity and execution time.
  • 14.
    Programming in CUnit-III BCA Semester I 14 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Declaring Structure Variables Structure variables can be declared in two ways: 1)Method 1 – After structure definition: struct Student { int rollno; char name[20]; float marks; }; struct Student s1, s2; // declaring variables 2)Method 2 – Along with structure definition: struct Student { int rollno; char name[20]; float marks; } s1, s2; Initializing Structure Members 1) Initialize a structure at the time of declaration: #include <stdio.h> // Define the structure struct Student { int rollno; char name[20]; float marks; };
  • 15.
    Programming in CUnit-III BCA Semester I 15 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca int main() { // Declare and initialize structure variables struct Student s1 = {101, "Arun", 85.5}; struct Student s2 = {102, "Riya", 92.0}; // Display values of s1 printf("Student 1 Details:n"); printf("Roll Number: %dn", s1.rollno); printf("Name: %sn", s1.name); printf("Marks: %.2fnn", s1.marks); // Display values of s2 printf("Student 2 Details:n"); printf("Roll Number: %dn", s2.rollno); printf("Name: %sn", s2.name); printf("Marks: %.2fn", s2.marks); return 0; } 2) assign values later: s1.rollno = 102; strcpy(s1.name, "Meena"); // for strings use strcpy() s1.marks = 90.0; Accessing Structure Members Members are accessed using the dot operator (.)
  • 16.
    Programming in CUnit-III BCA Semester I 16 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca III) Unions Introduction: • A union in C is a user-defined data type similar to a structure, but all members share the same memory location. • Only one member can hold a value at a time. Definition: A union is a C data type where all members share the same memory location, allowing only one active value at a time. Memory Allocation: • The memory allocated for a union equals the size of its largest member. • Assigning a value to one member overwrites the previous value stored in the union Applications of Unions 1. Save memory in programs with limited resources. 2. Share memory in embedded systems and device drivers. 3. Use the same data in different ways, like bit fields or packets. 4. Access the same memory as different data types (type punning). 5. Help in designing compilers and operating systems efficiently. Advantages/Need of Unions in C 1. Efficient memory usage, as all members share the same memory. 2. Handle different data types at different times using the same memory. 3. Useful in embedded systems and low-level programming where memory is limited. 4. Facilitates type conversion, e.g., accessing the same data as integer or float. 5. Optimized storage when only one value is needed at a time.
  • 17.
    Programming in CUnit-III BCA Semester I 17 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Disadvantages of Unions 1. Only one member can hold a value at a time. 2. Assigning a value to one member overwrites the previous value. 3. Cannot store multiple values simultaneously. 4. Accessing the wrong member may lead to unexpected results. 5. Not suitable when multiple data elements need to be stored concurrently. Declaration of Union Unions are declared using the keyword union. Syntax: union UnionName { data_type member1; data_type member2; ... data_type memberN; }; Initialization of Union 1)Method 1 – At the time of declaration: #include <stdio.h> // Define the union union Data { int i; float f; char str[20]; };
  • 18.
    Programming in CUnit-III BCA Semester I 18 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca int main() { // Method 1: Initialize at the time of declaration union Data d1 = {10}; // Initializes the first member 'i' // Access and display the value printf("Value of i: %dn", d1.i); return 0; } 2) Method 2 – Assigning later: int main() { // Declare a union variable union Data d2; // Assign integer value d2.i = 10; printf("After assigning integer:ni = %dnn", d2.i); // Assign float value d2.f = 5.5; printf("After assigning float:nf = %.2fnn", d2.f); // Assign string value strcpy(d2.str, "BCA"); printf("After assigning string:nstr = %sn", d2.str); return 0; }
  • 19.
    Programming in CUnit-III BCA Semester I 19 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Comparison of Arrays, Structures, and Unions in C Arrays Structures Unions 1. Store multiple values of the same data type. 1. Can store multiple variables of different data types. 1. Can store multiple variables of different types, but only one value at a time. 2. Size is fixed at the time of declaration. 2. Size depends on all members combined. 2. Size is equal to the largest member. 3. Elements are accessed using indices. 3. Members are accessed using the dot (.) operator. 3. Members are accessed using the dot (.) operator. 4. All elements occupy separate memory locations. 4. Each member has its own memory location. 4. All members share the same memory location. 5. Used for storing lists, matrices, or sequences of similar data. 5. Used to represent real- world entities logically. 5. Used for memory-efficient storage where only one value is needed at a time. 6. Supports traversal, searching, and sorting operations. 6. Can be nested or combined with arrays and pointers. 6. Efficient in low-memory applications like embedded systems. 7. Applications: storing student marks, employee salaries, matrices. Applications: storing student records, book details, employee profiles. Applications: type punning, sharing memory in embedded systems, interpreting data in multiple formats. *** *** ***