0% found this document useful (0 votes)
1 views

Introduction to Data Structures

The document provides an introduction to data structures, explaining their importance in organizing and managing data efficiently. It categorizes data structures into linear (arrays, linked lists, stacks, queues) and non-linear (trees, graphs, hash tables) types, and discusses their applications. Additionally, it covers the declaration, initialization, and usage of one-dimensional and two-dimensional arrays in programming.

Uploaded by

Kumuda R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introduction to Data Structures

The document provides an introduction to data structures, explaining their importance in organizing and managing data efficiently. It categorizes data structures into linear (arrays, linked lists, stacks, queues) and non-linear (trees, graphs, hash tables) types, and discusses their applications. Additionally, it covers the declaration, initialization, and usage of one-dimensional and two-dimensional arrays in programming.

Uploaded by

Kumuda R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Introduction to Data Structures(BCS654A)

A data structure is a specialized format for organizing, managing, and storing data
efficiently. It defines the way data is stored, accessed, and manipulated in a program.
The choice of a data structure affects the efficiency of algorithms and the overall
performance of a program.

Types of Data Structures


Data structures can be broadly classified into two types:
Linear Data Structures
Elements are arranged in a sequential manner.
🔹 Array – A fixed-size collection of similar data types stored at contiguous memory
locations.
🔹 Linked List – A dynamic data structure where elements (nodes) are linked using
pointers.
🔹 Stack – A LIFO (Last In, First Out) structure where insertion and deletion happen at
the top.
🔹 Queue – A FIFO (First In, First Out) structure where elements are added at the rear
and removed from the front.

Non-Linear Data Structures


Elements are arranged in a hierarchical or interconnected manner.
🔹 Trees – A hierarchical structure consisting of nodes, where each node has a parent-
child relationship. Example: Binary Tree, Binary Search Tree (BST), AVL Tree.
🔹 Graphs – A collection of nodes (vertices) connected by edges, used to model
networks, relationships, and complex structures.
🔹 Hash Tables – A structure that stores key-value pairs and allows fast access using a
hash function.

Why Are Data Structures Important?


Efficient Data Management – Organizing and storing data effectively.
Faster Computation – Optimizing search, insertion, and deletion operations.
Scalability – Handling large-scale data efficiently.
Algorithm Optimization – Choosing the right data structure improves algorithm
performance.

Introduction: Introduction to arrays: one-dimensional arrays, two dimensional arrays,


initializing two dimensional arrays, Multidimensional arrays.

INTRODUCTION

 An array is a group of related data items that share a common name. For instance, we
can define an array name salary to represent a set of salaries of a group of employees.

 A particular value is indicated by writing a number called index number of subscript


in brackets after the array name. For example,

o salary[10]
o represents the salary of the 10th employee.
 While the complete set of values is referred to as an array, the individual values are
called elements. Arrays can be of any variable type.

 The ability to use a single name to represent a collection of items and to refer to an
item by specifying the item number enables us to develop concise and efficient
programs. For example, a loop with the subscript as the control variable can be used
to read the entire array, perform calculations and, print out the results.

ONE-DIMENSIONAL ARRAYS
 A list of items can be given one variable name using only one subscript and such a
variable is called single-subscripted variable or a one-dimensional array.

Accessing and Storing Elements


 The subscripted variable xi refers to the ith element of x. In C, single-subscripted
variable xi can be expressed as
o x[1], x[2], x[3] ..........x[n]
 The subscript can begin with number 0. That is x[0] is allowed.
 For example, if we want to represent a set of five numbers, say (35, 40, 20, 57, 19), by
an array variable number, then we may declare the variable number as follows
int number[5];
and the computer reserves five storage locations as shown below:

Declaration of Arrays
 Like any other variable, arrays must be declared before they are used. The general
form of array declaration is
type variable-name[size];
 The type specifies the type of element that will be contained in the array, such as int,
float, or char and the size indicates the maximum number of elements that can be
stored inside the array. For example,
float height[50];
 declares the height to be an array containing 50 real elements. Any subscripts 0 to 49
are valid. Similarly,
int group[10];
 declares the group as an array to contain a maximum of 10 integer constants.
Remember, any reference to the arrays outside the declared limits would not
necessarily cause an error. Rather, it might result in unpredictable program results.
 The C language treats character strings simply as arrays of characters. The size in a
character string represents the maximum number of characters that the string can
hold. For instance,
char name[10];
 declares the name as a character array (string) variable that can hold a maximum of 10
characters.Suppose we read the following string constant into the string variable
name.
“WELL DONE”
 Each character of the string is treated as an element of the array name and is stored in
the memory as follows:


 When the compiler sees a character string, it terminates it with an additional null
character. Thus, the element name[9] holds the null character ‘\0’ at the end. When
declaring character arrays, we must always allow one extra element space for the null
terminator.
Initialization of Arrays
 We can initialize the elements of arrays in the same way as the ordinary variables
when they are declared.
 The general form of initialization of arrays is:
static type array-name[size] = { list of values };
 The values in the list are separated by commas. For example, the statement
static int number[3] = { 0,0,0 };
 will declare the variable number as an array of size 3 and will assign zero to each
element. If the number of values in the list is less than the number of elements, then
only that many elements will be initialized. The remaining elements will be set to zero
automatically. For instance,
static float total[5] = {0.0,15.75, 10};
 will initialize the first three elements to 0.0, 15.75, and 10.0 and the remaining two
elements to zero.
For example, the statement
 static int counter[ ] = {1,1,1,1};
will declare the counter array to contain four elements with initial values 1. This
approach works fine as long as we initialize every element in the array.
 Character arrays may be initialized in a similar manner. Thus, the statement
char name[ ] = {‘J’, ‘o’, ‘h’, ‘n’};
 declares the name to be an array of four characters, initialized with the string “John”.
Initialization of arrays in C suffers two drawbacks.
 There is no convenient way to initialize only selected elements.
 There is no shortcut method for initializing a large number of array elements like the
one available in FORTRAN.

8.3 TWO-DIMENSIONAL ARRAYS

 Consider the following data table, which shows the value of the sales of three items
by four salesgirls:
 The table contains a total of 12 values, three in each line. We can think of this table as
a matrix consisting of four rows and three columns. Each row represents the values of
sales by a particular salesgirl and each column represents the values of sales of a
particular item.
 In mathematics, we represent a particular value in a matrix by using two subscripts
such as vij. Here v denotes the entire matrix and vij refers to the value in the ith row
and jth column. For example, in the above table v23 refers to the value 325.
 C allows us to define such tables of items by using two-dimensional arrays. The table
discussed above can be defined in C as
v[4][3]
 Two-dimensional arrays are declared as follows:
type array_name [row_size][column_size];

8.4 INITIALIZING TWO-DIMENSIONAL ARRAYS


 Like the one-dimensional arrays, two-dimensional arrays may be initialized by
following their declaration with a list of initial values enclosed in braces. For
example,
static int table[2][3] = {0,0,0,1,1,1};
 initializes the elements of the first row to zero and the second row to one. The
initialization is done row by row. The above statement can be equivalently written as
static int table[2][3] = {{0,0,0}, {1,1,1}};
by surrounding the elements of each row by braces.
 We can also initialize a two-dimensional array in the form of a matrix as shown
below:
static int table[2][3] = {
{0,0,0,},
{1,1,1}
}
If the values are missing in initializer, they are automatically set to zero. For instance,
the statement
static int table[2][3] = {
{1,1},
{2}
};
 will initialize the first two elements of the first row to one, the first element of the
second row to two, and all other elements to zero.
 When all the elements are to be initialized to zero, the following short-cut method
may be used.
static int m[3][5] = { {0}, {0} {0} };
 The first element of each row is explicitly initialized to zero while other elements are
automatically initialized to zero.

8.5 MULTIDIMENSIONAL ARRAYS


 C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multidimensional array is
type array_name[s1][s2][s3].....[sm];
 where si is the size of the ith dimension. Some example are:
int survey[3][5][12];
float table[5][4][5][3];
 survey is a three-dimensional array declared to contain 180 integer type
elements.Similarly table is a four-dimensional array containing 300 elements of
floating-point type.
 The array survey may represent a survey data of rainfall during the last three years
from January to December in five cities.
 If the first index denotes year, the second city and the third month, then the element
survey[1][2][9] denotes the rainfall in the month of October during the second year in
city-3.
 Remember that a three-dimensional array can be represented as a series of two-
dimensional arrays as shown below:

Prog
rams:
Example 8.1:
Write a program using a single-subscripted variable to evaluate the following
expressions/sum of squares of numbers.

#include <stdio.h>

int main() {

int i;
float x[10], total = 0.0;

/* Reading values into the array */

printf("ENTER 10 REAL NUMBERS:\n");

for (i = 0; i < 10; i++) {

scanf("%f", &x[i]);

/* Computation of total (sum of squares) */

for (i = 0; i < 10; i++) {

total += x[i] * x[i];

/* Printing x[i] values and total */

printf("\nValues and their indices:\n");

for (i = 0; i < 10; i++) {

printf("x[%2d] = %5.2f\n", i + 1, x[i]);

printf("\nTotal sum of squares = %.2f\n", total);

return 0;

}
Output:

Example 8.2

Given below is the list of marks obtained by a class of 50 students in an annual


examination.

43 65 51 27 79 11 56 61 82 09

25 36 07 49 55 63 74 81 49 37

40 49 16 75 87 91 33 24 58 78

65 56 76 67 45 54 36 63 12 21

73 49 51 19 39 49 68 93 85 59

Write a program to count the number of students belonging to each of the following
groups of marks:

0-9, 10-19, 20-29, ......., 100.


Program:

#include <stdio.h>

#define MAXVAL 50

#define COUNTER 11

int main() {

float value[MAXVAL] = {

43, 65, 51, 27, 79, 11, 56, 61, 82, 9,

25, 36, 7, 49, 55, 63, 74, 81, 49, 37,

40, 49, 16, 75, 87, 91, 33, 24, 58, 78,

65, 56, 76, 67, 45, 54, 36, 63, 12, 21,

73, 49, 51, 19, 39, 49, 68, 93, 85, 59

};

int i, low, high;

int group[COUNTER] = {0};

/* Counting frequency of groups */

for (i = 0; i < MAXVAL; i++) {

int index = (int)(value[i] + 0.5) / 10; // Round and categorize

/* Ensure index is within valid range */

if (index >= 0 && index < COUNTER) {

++group[index];

/* Printing frequency table */


printf("\nGROUP RANGE FREQUENCY\n\n");

for (i = 0; i < COUNTER; i++) {

low = i * 10;

high = (i == 10) ? 100 : low + 9;

printf(" %2d %3d to %3d %d\n", i + 1, low, high, group[i]);

return 0;

Output:
Example 8.3

Write a program using a two-dimensional array to compute and print the


following information from the table of data discussed above:

(a) Total value of sales by each girl.

(b) Total value of each item sold.

(c) Grand total of sales of all items by all girls.

Program:

#include <stdio.h>

#define MAXGIRLS 4

#define MAXITEMS 3

int main() {

int value[MAXGIRLS][MAXITEMS];

int girl_total[MAXGIRLS], item_total[MAXITEMS];

int i, j, grand_total;

/* Reading values and computing girl_total */


printf("Input data\n");

printf("Enter values, one at a time, row-wise:\n\n");

for (i = 0; i < MAXGIRLS; i++) {

girl_total[i] = 0;

for (j = 0; j < MAXITEMS; j++) {

scanf("%d", &value[i][j]);

girl_total[i] += value[i][j];

/* Computing item_total */

for (j = 0; j < MAXITEMS; j++) {

item_total[j] = 0;

for (i = 0; i < MAXGIRLS; i++) {

item_total[j] += value[i][j];

/* Computing grand_total */

grand_total = 0;

for (i = 0; i < MAXGIRLS; i++) {

grand_total += girl_total[i];

}
/* Printing results */

printf("\nGIRLS TOTALS\n\n");

for (i = 0; i < MAXGIRLS; i++) {

printf("Salesgirl[%d] = %d\n", i+1, girl_total[i]);

printf("\nITEM TOTALS\n\n");

for (j = 0; j < MAXITEMS; j++) {

printf("Item[%d] = %d\n", j+1, item_total[j]);

printf("\nGrand Total = %d\n", grand_total);

return 0;

}
#include <stdio.h>

#define ROWS 5

#define COLUMNS 5
int main() {

int row, column, product[ROWS][COLUMNS];

int i, j;

printf("MULTIPLICATION TABLE\n\n");

/* Printing column headers */

printf(" ");

for (j = 1; j <= COLUMNS; j++) {

printf("%4d", j);

printf("\n");

/* Printing horizontal line */

printf(" ---------------------\n");

/* Filling and printing the multiplication table */

for (i = 0; i < ROWS; i++) {

row = i + 1;

printf("%2d |", row); // Row label

for (j = 0; j < COLUMNS; j++) {

column = j + 1;
product[i][j] = row * column;

printf("%4d", product[i][j]); // Print the product

printf("\n");

return 0;

Introduction to Pointers: Pointer concepts, accessing variables through pointers,


Dynamic memory allocation, pointers applications.

Pointers

 The basic data types in C language are int, float, char, double and void. Pointer is a
special data type which is derived from these basic data types, So, pointer is called
derived data type. The pointer takes the values from 0 to 65535 if the size of the RAM
is 64K.

Pointer concepts

-pointer constants

-pointer values

-pointer variables

2.2.1 Pointer constants

 As we store any information in our memory, the computer stores information in


computer memory. The computer memory is divided into a number of locations called
storage cells. Each location can hold one byte of information and each location is
associated with address. Let us assume size of memory is 64K where

1K = 1024 bytes. So, total number of memory locations = 64K = 64 x 1K

= 64 x 1024 bytes

= 65536 locations

Logically, all 65536 locations in computer memory are numbered sequentially from 0 to
65535 but, physically they are divided into even bank and odd bank. Even bank is set of
memory locations with even addresses and odd bank is set of memory locations with odd
addresses as shown below:
These memory addresses are called pointer constants. We can not change them; but, we can
only use them to store data values.

For example, in the above memory organization, the addresses ranging from 0 to 65535 are
pointer constants.

Note: The address of a memory location is a pointer constant and can not be changed.

2.2.2 Pointer values

Suppose, we have the following declaration:

int i = 100, j = 200, k = 300;

This declaration tells the compiler to perform the following activities:

• Reserve space for three integer values in memory

• Associate the variables i, j and k with these memory locations

• Store 100, 200 and 300 at the locations i, j and k respectively as shown below:

 The address of the variable can not be accessed directly. The address of the variable
can be obtained using address operator (denoted by &) in C language.

Note: The address operator can be used with any variable that can be placed on the left side
of an assignment operator. Since constants, expressions and array names can not be used on
the left hand side of the assignment and hence accessing address is invalid for constants,
expressions and array names. The following are invalid:

Definition: Memory is divided into number of storage cells called locations. All the locations
in computer memory are numbered sequentially from 0 to 65535 (with memory size of 64K).

 Out of these addresses, the system assigns some addresses of the memory locations to
the variables. These memory addresses assigned to variables by the system are called
pointer values.
 For example, the addresses 65530, 65532 and 65534 which are assigned to the
variables i, j and k are pointer values. These pointer values can be obtained using
address operator (&). Using &i, &j and &k we can obtain pointer values 65530,
65532 and 65534.

Note: Without address operator (&), it is not possible to obtain the pointer value of a
variable.

Note: The pointer values (i.e., the addresses assigned to variables) may vary each time the
program is executed. That is, the address of the variable may change from one run of the
program to another.

2.2.3 Pointer variable

Definition: A variable which holds address of another variable is called <pointer variable. In
other words, pointer variable is a variable which holds pointer value (i.e., address of a
variable). For example, if i is a variable and address of i is stored in a variable p as shown
below:

p=&i;

then the variable p is called a pointer variable. The memory organization after executing the
above statement is shown below:

2.3 Accessing variables through pointers

2.3.1 Pointer declaration and Definition

The syntax to declare a pointer variable is shown below: .


2.3.2 Dangling pointers

For example, consider the following declaration:

int *p;

This indicates that p is a pointer variable and the corresponding memory location should
contain address of an integer variable. But, the declaration will not initialize the memory
location and memory contains garbage value as shown below:

Deflnitione e, pointer variable should contain a valid address. A pointer variable which does
not contain a valid address is called dangling pointer.

2.3.3 Initializing a pointer variable

 Initialization of a pointer variable is the process of assigning the 'address of a variable


to a pointer variable. The initialization of a pointer variable can be done using
following three steps:

Step. 1: Declare a data variable

Step 2: Declare a pointer variable

Step 3: Assign address of a data variable to pointer variable

 using & operator and assignment operator


 Note that the steps 1 and 2 can be interchanged i.e., we can first declare a pointer
variable, then declare a data variable and then initialize the pointer variable.
NULL pointer

 A NULL pointer is defined as a special pointer value that points to nowhere in the
memory. If it is too early in the code to assign a value to the pointer,then it is better to
assign NULL (i.e., \0 or 0) to the pointer.
 For example, consider the following code:
#include <stdio.h>
int *p = NULL;
 Here, the pointer variable p is a NULL pointer. This indicates that the pointer
variable p does not point to any part of the memory. The value for NULL is defined in
the header file "stdio.h". Instead of using NULL we can also use '\0' or O.
 The programmer can access the data using the pointer variable p if and only it does
not contain NULL. The error condition can be checked using the following statement:
if (p = = NULL)
printf("p does not point to any memory]n");
printf("Access the value of p\n");
else {
…..
}

2.3.5 Accessing variables through,pointers .


 The value of a variable can be accessed using pointer variable using unary operator *
(called asterisk).
 This operator is called indirection operator or dereferencing operator.
 For example, consider the following program segment:
int x = 100, y;
int *p;// Address of x is stored in pointer variable p
p=&x;// Since p has the address of x, the value of data
y= *p;// * variable x i.e, 100 is copied into y *1

Note: By specifying *p, the value of the variable whose address is stored in p can be
accessed. Here, p should be a pointer variable.
2.5 Pointer applications

 Pointers are a fundamental concept in C that provide direct memory access


and manipulation capabilities. They allow efficient handling of data structures,
dynamic memory allocation, and function operations. Two important
applications of pointers include their use with arrays and dynamic memory
allocation.

1. Pointers with Arrays


 An array is a collection of elements stored in contiguous memory locations. In
C the array name itself acts as a pointer to its first element. Pointers can be
used to traverse and manipulate arrays efficiently.
Concepts:
 The name of an array is a constant pointer to its first element.
 Pointer arithmetic allows movement between elements in an array.
 Pointers provide a way to dynamically access and modify elements.
Advantages:
 Efficient traversal of array elements.
 No need to use explicit indexing (arr[i]).
 Optimized memory access for large datasets.

2. Pointers in Dynamic Memory Allocation


 Dynamic memory allocation refers to allocating memory during program
execution rather than at compile time. This is done using functions like
malloc(), calloc(), realloc(), and free() in C.
Concepts:
 malloc(size): Allocates size bytes of memory and returns a pointer to the
allocated space.
 calloc(n, size): Allocates memory for n elements of size bytes each and
initializes them to zero.
 realloc(ptr, new_size): Resizes previously allocated memory.
 free(ptr): Deallocates dynamically allocated memory.
Advantages:
 Memory is allocated as needed, reducing wastage.
 Enables dynamic data structures like linked lists and trees.
 Provides flexibility to handle varying data sizes.

Dynamic memory allocation


 Dynamic memory allocation is the process of allocating memory during
execution time (i.e., run time). This is a pretty unique feature of C when
compared
with other high level languages.
 This allocation technique uses predefined functions to allocate and release
memory for data during execution time. So, if there is an
unpredictable storage requirement, then the dynamic allocation technique is
used.
 Dynamic allocation will be used commonly in the following data structures:
• dynamic arrays
• linked lists, trees

Difference between static memory allocation and dynamic memory allocation


malloc(size)

 This function allows the program to allocate memory explicitly as and when
required and the exact amount needed during execution. This function
allocates a block of memory. The size of the block is the number of bytes
specified in the parameter. The syntax is shown below:

#include <stdlib.h> /* Prototype definition of malloc*/

ptr = (data_type *) malloc(size);

where
• ptr is a pointer variable of type data_type

• data_type can be any of the basic data type or user defined data type

• size is the number of bytes required

• On successful allocation, the function returns the address of first byte of allocated memory.
Since address is returned, the return type is a void pointer. By type casting appropriately we
can use it to store integer, float etc.

• If specified size of memory is not available, the condition is called "overflow of memory".
In such case, the function returns NULL.

void function_name()

ptr = (data_type *) malloc(size);

if (ptr = NULL)

printf("Insufficient memory\n");

exit(0);

}
calloc{n, size)

 This function is used to allocate multiple blocks of memory. Here, calloc -


stands for contiguous allocation of multiple blocks and is mainly used to
allocate memory for arrays.
 The number of blocks is determined by the first parameter n. The size of each
block is equal to the number of bytes specified in the parameter i.e., size.
Thus, total number of bytes allocated is n*size and all bytes will be initialized
to O.

The syntax is shown below:


#include <stdlib.h> /* Prototype definition of calloc() is available */

ptr = (data_type *) calloc{n, size);

where

• ptr is a pointer variable of type data_type

• data_type can be any of the basic data type or user defined data type

• n is the number of blocks to be allocated

• size is the number of bytes in each block

 On successful allocation, the function returns the address of first byte of allocated
memory. Since address is returned, the return type is a void pointer. By type casting
appropriately we can use it to store integer, float etc.
 "If specified size of memory is not available, the condition is called "overflow of
memory". In such case, the function returns NULL.

void function_name()
{
ptr = (data_type *) calloc(size);
if (ptr = NULL)
{
printf("Insufficient memory\n");
exit(0);
}
}
realloc(ptr, size)

 Before using this function, the memory should have been allocated using malloc() or
calloc(). Sometimes, the allocated memory may not be sufficient and we may require
additional memory space. Sometimes, the allocated memory may be much larger and
we want to reduce the size of allocated memory.
 In both situations, the size of allocated memory can be changed using realloc() and
the process is called reallocation of memory. The reallocation is done as shown
below:
• realloc() changes the size of the block by extending or deleting the memory at the end of the
block.

• If the existing memory can be extended, ptr value will not be changed,If the memory can
not be extended, this function allocates a completely new block and copies the contents of
existing memory block into new memory block and then deletes the old memory block. The
syntax is shown below:

#include <stdlib.h> /* Prototype definition of realloc() is available */

ptr = {data_type *)realloc(ptr, size);

where

• ptr is a pointer to a block of previously allocated memory either using

malloct) or calloct).

• size is new size of the block

if (ptr == NULL)

{ /* Memory is not allocated */

Printf(“Insufficient memory\n");

return;

}
free(ptr)

 This function is used to de-allocate (or free) the allocated block of memory which is
allocated by using the functions calloc(), malloc() or realloc(). It is the responsibility a
programmer to de-allocate memory whenever it is not required by the program and
initialize ptr to NULL. The syntax is shown below:

#include <stdlib.h> /* Prototype definition of free() is available */

free(ptr);

ptr =NULL;

STRUCTURE DEFINITION-DECLARING STRUCTURES

 A structure in C is a user-defined data type that allows grouping different types of


data under a single name. It is used to store multiple related variables of different
types in a single entity.
 A structure definition creates a format that may be used to declare structure variables.
Let us use an example to illustrate the process of structure definition and the creation
of structure variables. Consider a book database consisting of book name, author,
number of pages, and price. We can define a structure to hold this information as
follows:

struct book_bank

char title[20];

char author[15];

int pages;

float price;

};

 The keyword struct declares a structure to hold the details of four fields, namely title,
author, pages,and price. These fields are called structure elements or members. Each
member may belong to a different type of data. book_bank is the name of the
structure and is called the structure tag. The tag name may be used subsequently to
declare variables that have the tag’s structure.

 We can declare structure variables using the tag name anywhere in the program. For
example, the statement
struct book_bank book1, book2, book3;

declares book1, book2, and book3 as variables of type struct book_bank.

Each one of these variables has four members as specified by the template. The complete
declaration might look like this:

struct book_bank

char title[20];

char author[15];

int pages;

float price;

};

struct book_bank book1, book2, book3;

Remember that the members of a structure themselves are not variables. They do not occupy
any memory until they are associated with the structure variables such as book1.

In defining a structure you may note the following syntax:

1. The template is terminated with a semicolon.

2. While the entire declaration is considered as a statement, each member is declared


independently

for its name and type in a separate statement inside the template.

3. The tag name such as book_bank can be used to declare structure variables of its type, later
in the program.

It is also allowed to combine both the template declaration and variables declaration in one
statement.

The declaration

struct book_bank

{
char title[20];

char author[15];

int pages;

float price;

} book1, book2, book3;

is valid. The use of tag name is optional. For example,

struct

........

........

........

} book1, book2, book3;

declares book1, book2, and book3 as structure variables representing three books, but does
not include a tag name for later use in declarations.

 Normally, structure definitions appear at the beginning of the program file, before any
variables or functions are defined. They may also appear before the main, along with
macro definitions, such as #define. In such cases, the definition is global and can be
used by other functions as well.

GIVING VALUES TO MEMBERS

 We can assign values to the members of a structure in a number of ways. As


mentioned earlier, the members themselves are not variables. They should be linked to
the structure variables in order to make them meaningful members. For example, the
word title, has no meaning where as the phrase “title of book3” has a meaning.
 The link between a member and a variable is established using the member operator
“.” which is also known as “dot operator” or “period operator”. For
example,book1.price
is the variable representing the price of book1 and can be treated like any other
ordinary variable. Here is how we would assign values to the members of book1:
strcpy(book1.title, “BASIC”);
strcpy(book1.author, “Balagurusamy”);
book1.pages = 250;
book1.price = 28.50;
We can also use scanf to give the values through the keyboard.
scanf(“%s\n”, book1. title);
scanf("%d\n”, &book1.pages);
are valid input statements.

STRUCTURE INITIALIZATION

main( )

static struct

int weight;

float height;

student = {60, 180.75};

.....

.....

 This assigns the value 60 to student.weight and 180.75 to student.height. There is a


one-to-one correspondence between the members and their initializing values.
 A lot of variation is possible in initializing a structure. The following statements
initialize two structure variables. Here, it is essential to use a tag name.

main( )
{

struct st_record

int weight;

float height;

};

static struct st_record student1 = {60, 180.75};

static struct st_record student2 = {53, 170.60};

.....

.....

Another method is to initialize a structure variable outside the function as shown below:

struct st_record /* No static word */

int weight,

float height;

} student1 = {60, 180.75};

main( )

static struct st_record student2 = {53, 170.60};

.....

.....

}
COMPARISON OF STRUCTURE VARIABLES

Two variables of the same structure type can be compared the same way as ordinary
variables. If

person1 and person2 belong to the same structure, then the following operations are valid:

ARRAYS OF STRUCTURES

struct class student[100];

defines an array called student, that consists of 100 elements. Each element is defined to be of
the type struct class. Consider the following declaration:

struct marks

int subject1;

int subject2;

int subject3;

};

main( )

static struct marks student[3] ={{45,68,81}, {75,53,69}, {57,36,71}};

This declares the student as an array of three elements student[0], student[1], and student[2]
and

initializes their members as follows:

student[0].subject1 = 45;
student[0].subject2 = 68;

. . . ..

. . . ..

student[2].subject3 = 71;

ARRAYS WITHIN STRUCTURES

struct marks

int number;

float subject[3];

} student[2];

Here, the member subject contains three elements, subject[0], subject[1] and subject[2].
These

elements can be accessed using appropriate subscripts. For example, the name

student[1].subject[2];

would refer to the marks obtained in the third subject by the second student.

STRUCTURES WITHIN STRUCTURES-NESTED STRUCTURES

Structures within a structure means nesting of structures. Nesting of structures is permitted in


C. Let us consider the following structure defined to store information about the salary of
employees.

struct salary

char name[20];

char department[10];
int basic_pay;

int dearness_allowance;

int house_rent_allowance;

int city_allowance;

employee;

This structure defines name, department, basic pay and three kinds of allowances. We can
group all the items related to allowance together and declare them under a substructure as
shown below:

struct salary

char name[2];

char department[10];

struct

int dearness;

int house_rent;

int city;

allowance;

employee;

 The salary structure contains a member named allowance which itself is a structure
with three members.
 The members contained in the inner structure namely dearness, house_rent, and city
can be referred to as
employee.allowance.dearness

employee.allowance.house_rent

employee.allowance.city

 An inner-most member in a nested structure can be accessed by chaining all the


concerned structure variables (from outer-most to inner-most) with the member using
dot operator. The following being invalid:

employee.allowance (actual member is missing)


employee.house_rent (inner structure variable is missing)

UNIONS

 Unions are a concept borrowed from structures and therefore follow the same syntax
as structures.
However, there is major distinction between them in terms of storage. In structures,
each member has its
own storage location, whereas all the members of a union use the same location. This
implies that,
although a union may contain many members of different types, it can handle only
one member at a time.
Like structures, a union can be declared using the keyword union as follows:
union item
{
int m;
float x;
char c;
} code;
This declares a variable code of type union item. The union contains three members,
each with a
different data type. However, we can use only one of them at a time. This is due to the
fact that only one
location is allocated for a union variable, irrespective of its size.

 To access a union member, we can use the same syntax that we use for structure
members. That is,

code.m

code.x

code.c

are all valid member variables. During accessing, we should make sure that we are accessing
the member whose value is currently stored. For example, the statements such as

code.m = 379;

code.x = 7859.36;

printf(“%d”, code.m);

would produce erroneous output (which is machine dependent).

 In effect, a union creates a storage location that can be used by any one of its
members at a time. When a different member is assigned a new value, the new value
supercedes the previous member’s value.
 Unions may be used in all places where a structure is allowed. The notation for
accessing a union member which is nested inside a structure remains the same as for
the nested structures.

typedef
 C provides the typedef keyword that allows you to specify a new name for a data type
already provided in the C programming language. In other words, you can use the
typedef keyword to specify an identifier for an existing data type. The declaration for
the typedef keyword is:

typedef data type newname

In the above example, data type represents the existing data type for which you want to
specify an

identifier and newname refers to that identifier.

example:

typedef int num;

Here, int is the data type available in C and a new identifier num has been specified for this
data type.

The following code shows an example for using the typedef keyword:

#include <stdio.h>

#include <conio.h>

int main(void)

typedef int num;

num a, b, add;

a=10;

b=20;

add=0;

add = a+b;

clrscr();

printf(“The sum of %d and %d is: %d”,a,b,add);

getch();
return 0;

Output:type is int so 10+20=30

SIZE OF STRUCTURES

 We normally use structures, unions, and arrays to create variables of large sizes. The
actual size of these variables in terms of bytes may change from machine to machine.
We may use the unary operator sizeof to tell us the size of a structure (or any
variable). The expression

sizeof (struct x)

will evaluate the number of bytes required to hold all the members of the structure x. If y is a
simple

structure variable of type struct x, then the expression

sizeof(y)

would also give the same answer. However, if y is an array variable of type struct x, then

sizeof(y)

would give the total number of bytes the array y requires.

 This kind of information would be useful to determine the number of records in a


database. For example, the expression

size of(y)/sizeof(x)

would give the number of elements in the array y.

Programs on Structures:

Define a structure type, struct personal, that would contain person name, date of joining
and salary. Using this structure, write a program to read this information for one
person from the keyboard and print the same on the screen.
#include <stdio.h>

struct personal {

char name[20];

int day;

char month[10];

int year;

float salary;

};

int main() {

struct personal person;

printf("Input Values (Name, Day, Month, Year, Salary):\n");

scanf("%19s %d %9s %d %f",

person.name,

&person.day,

person.month,

&person.year,

&person.salary);

printf("%s %d %s %d, %.2f\n",


person.name,

person.day,

person.month,

person.year,

person.salary);

return 0;

Output:

Write a program to illustrate the comparison of structure variables.

#include <stdio.h>

#include <string.h>

struct person {

char name[20];
int age;

float salary;

};

int main() {

struct person p1 = {"Alice", 30, 50000.0};

struct person p2 = {"Alice", 30, 50000.0};

// Compare members individually

if (strcmp(p1.name, p2.name) == 0 && p1.age == p2.age && p1.salary == p2.salary) {

printf("Structures are equal.\n");

} else {

printf("Structures are not equal.\n");

return 0;

Output:
For the student array discussed above, write a program to calculate the subjectwise and
studentwise totals and store them as a part of the structure.

#include <stdio.h>

struct marks {

int sub1;

int sub2;

int sub3;

int total;
};

int main() {

int i;

// Initialize student data

static struct marks student[3] = {

{45, 67, 81, 0},

{75, 53, 69, 0},

{57, 36, 71, 0}

};

// Initialize total structure

static struct marks total = {0, 0, 0, 0};

// Calculate individual totals and sum across students

for (i = 0; i < 3; i++) {

student[i].total = student[i].sub1 + student[i].sub2 + student[i].sub3;

total.sub1 += student[i].sub1;

total.sub2 += student[i].sub2;

total.sub3 += student[i].sub3;

total.total += student[i].total;

}
// Display student-wise totals

printf("STUDENT TOTAL\n\n");

for (i = 0; i < 3; i++) {

printf("Student[%d]: %d\n", i + 1, student[i].total);

// Display subject-wise totals

printf("\nSUBJECT TOTAL\n\n");

printf("Subject 1: %d\n", total.sub1);

printf("Subject 2: %d\n", total.sub2);

printf("Subject 3: %d\n", total.sub3);

// Display grand total

printf("\nGrand Total = %d\n", total.total);

return 0;

Output:

You might also like