Unit 5
Unit 5
TOPIC - 1
I) STRUCTURE: In C programming, a structure is a user-defined data type that allows grouping related
variables of heterogeneous data types under a single name. Each item within a structure is called a
"member," and it can be of any valid C data type, such as integer, float, character, or even another
structure.
Structures in C provide a convenient way to handle more complex data by bundling different
types of information into one unit. For example, if you need to store a student’s name, age, and grade,
you can use a structure called Student with members for each of these values. Structures make it easier
to manage and organize data logically, especially when dealing with multiple records of mixed data
types.
Using the struct keyword, structures are defined only once but can be used to create multiple
variables (instances) with the same structure, making them powerful tools for organizing and handling
data in C programs.
a) C Structure Definition: To use a structure in a program, you need to create variables of that
structure type, which are known as instances. You can define these structure variables either right
after declaring the structure or separately later in the program. This allows you to allocate
memory and work with specific data values for each instance, making it possible to organize and
manage different sets of structured information efficiently.
i) Structure Variable Declaration with Structure Template: To declare structure
variables immediately after defining the structure template. This approach combines the
structure definition and variable declaration in a single line. After listing the structure
members with their data types, you specify the variables directly after the closing brace.
Syntax: Example:
struct structure_name { struct str1
data_type member_name1; {
............................................. int i; char c; float f; char s[30];
............................................. }s1,s2,s3;
} variable1, variable2, ...;
ii) Structure Variable Declaration after Structure Template: To create variables for a
structure after defining it separately. Once you've declared the structure template, you can
then use the structure's name followed by the variable names to create as many instances
as you need. This allows you to set up the structure first and then create variables for it
later in the code.
Syntax:
struct structure_name variable1, variable2, .......;
Example:
struct str1 s1,s2,s3;
b) Access Structure Members: You can access the members of a structure by using the dot (`.`)
operator. This operator connects the structure variable to its specific member, allowing you to
read or modify the member's value. For example, if you have a structure variable called `student`
and a member `age`, you would access it with `student.age`. This method helps you work with
individual parts of the structure's data.
Syntax:
structure_name.member1; structure_name.member2;
II. NESTED STRUCTURES: Nested structures in C refer to structures within other structures. This
setup allows grouping related data more effectively by embedding one structure inside another, enabling
complex data relationships within a single structure type.
In C programming, nested structures offer a way to organize hierarchical or multi-layered data by
allowing one structure to contain another structure as a member. This is useful when dealing with data
that has a natural "parent-child" relationship. For example, if you’re designing a structure for a "Person,"
you might want to include an "Address" structure as a part of it. Using nested structures makes the code
more modular and organized by keeping related data together, making it easier to understand and
manage.
There are two primary methods for nesting structures:
a) Embedded Structure Nesting
b) Separate Structure Nesting.
a) Embedded Structure Nesting: In embedded structure nesting, the nested structure is directly
defined within the parent structure. This means that the nested structure only exists within the
context of the parent and cannot be used separately in other parts of the program.
Syntax: Example:
struct Parent { struct Parent {
data_type parent_member1; int parent_member1;
data_type parent_member2; float parent_member1;
struct Nested { struct Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
} nested_variable_name; } child;
}; };
b) Separate Structure Nesting: In separate structure nesting, the nested structure is declared
independently and then used as a member within the parent structure.
Syntax: Example:
struct Nested { struct Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
}; };
struct Parent { struct Parent {
data_type parent_member; int parent_member;
struct Nested child_member; struct Nested child;
}; };
Accessing Nested Members: To access members of a nested structure, the dot operator (.) is used twice
in succession: once for the parent structure variable and then for the nested structure’s member. This
allows you to drill down into the structure hierarchy to reach the desired member.
Syntax:
struct Parent parent_variable;
COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM
B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
parent_variable.nested_structure_variable.member_name = value;
Example:
struct Parent p; p.child.nested_member1 = 10;
III. ARRAYS OF STRUCTURES: In C programming, an "array of structures" is an effective way to
organize and handle large sets of data that include multiple types. An array is a collection of elements of
the same type, while a structure groups different data types together. By combining them, you create an
array in which each element is a structure containing various data fields.
This method is highly useful when dealing with complex, large-scale data because it allows for
easy storage, access, and modification of grouped information. Instead of managing each data item
individually, an array of structures keeps all related data in an organized, single format. This makes the
code simpler, more readable, and much easier to maintain, especially when handling extensive datasets
with multiple fields.
By defining a structure (e.g., Student) and creating an array of that structure, you can efficiently
manage large datasets, such as student records with names, roll numbers, and grades. This approach
simplifies data organization and access, making the code easier to maintain.
Declaration:
struct structure_name array_name[number_of_elements];
Initialization:
struct structure_name array_name[number_of_elements] = {v11, v12, ...}, {v21,
v22, ...}, .... };
For instance, imagine we have to store data for 50 students, including information like name, roll
number, and grades. If we were to declare each student individually, like struct Student student1,
student2, ..., student50;, it would be tedious and difficult to manage. Now, imagine an even larger
scenario with hundreds of students—this approach becomes unmanageable.
Example Code:
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int rollNumber;
};
void main() {
struct Student students[3];
strcpy(students[0].name, "Raj");
students[0].rollNumber = 1;
strcpy(students[1].name, "Ram");
students[1].rollNumber = 2;
strcpy(students[2].name, "Shyam");
students[2].rollNumber = 3;
for (int i = 0; i < 3; i++)
printf("Roll Number: %d, Name: %s\n", students[i].rollNumber, students[i].name);
}
IV. STRUCTURES AND FUNCTIONS: In C programming, structures are used to define custom data
types, which can hold multiple pieces of information of different types. Functions, on the other hand, are
blocks of code that perform specific tasks, and they can be used with structures to manipulate data more
effectively.
1. Passing Structures to Functions: Structures can be passed to functions in two ways. In pass
by value, a copy of the structure is passed, and changes inside the function don’t affect the
original structure. In pass by reference, a pointer to the structure is passed, allowing the function
to modify the original structure directly, making it more efficient. There are two primary ways to
pass structures to functions:
TOPIC - 2
VI) UNION: In C programming, a union is a user-defined data type that allows storing different types of
data in the same memory location. Unlike a structure, where each member has its own memory space, all
members of a union share the same memory space. This means only one member can hold a value at a
time. Unions in C provide a way to efficiently use memory when different types of data are needed, but
only one of them will be used at any given moment.
Unions are typically used when you need to store different data types, but only one type of data
will be needed at a time. For example, you might store an integer, a float, or a character in a union, but
only one of these values will be used at a time. This makes unions an efficient way to manage memory,
especially in systems with limited resources.
Using the union keyword, unions are defined only once, but multiple variables (instances) of the
same union can be created, making unions an efficient tool for managing memory when different types
of data are required.
a) C Union Definition: To use a union in a program, you need to create variables of that union
type, which are known as instances. You can define these union variables either right after
declaring the union or separately later in the program. This allows you to allocate memory and
work with specific data values for each instance, making it possible to organize and manage
different types of data efficiently.
i) Union Variable Declaration with Union Template: To declare union variables
immediately after defining the union template. This approach combines the union
definition and variable declaration in a single line. After listing the union members with
their data types, you specify the variables directly after the closing brace.
Syntax:
union union_name {
data_type member_name1;
VII. NESTED UNIONS: Nested unions in C refer to unions defined within other unions or structures.
This allows grouping related data efficiently by embedding one union inside another, enabling more
complex data relationships. Nested unions are useful in scenarios where different types of data, but only
one at a time, need to be grouped together within a structure or another union.
In C programming, nested unions allow you to organize hierarchical or multi-layered data by
allowing one union to be contained as a member of another union or structure. This is particularly useful
when dealing with complex data structures that involve mutually exclusive data types, but need to be
grouped together under a single name.
a) Embedded Union Nesting: In embedded union nesting, the nested union is directly defined
within the parent union or structure. This means the nested union exists only in the context of the
parent and cannot be used separately in other parts of the program.
Syntax: Example:
union Parent { union Parent {
data_type parent_member1; int parent_member1;
data_type parent_member2; float parent_member2;
union Nested { union Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
} nested_variable_name; } child;
}; };
Accessing Nested Union Members: To access members of a nested union, you use the dot operator (.)
twice in succession: once for the parent union or structure variable and once for the nested union's
member. This allows you to drill down into the nested structure or union hierarchy to reach the desired
member.
Syntax:
union Parent parent_variable;
parent_variable.nested_union_variable.member_name = value;
Example:
union Parent p;
p.child.nested_member1 = 10;
Declaration:
union union_name array_name[number_of_elements];
Initialization:
union union_name array_name[number_of_elements] = { {v11, v12, ...}, {v21, v22, ...}, ... };
For instance, imagine you need to store information like different types of values (integers, floats,
characters) for 50 entries. Declaring each value individually would be cumbersome and difficult to
manage. However, using an array of unions, you can efficiently store this data.
Example Code:
#include <stdio.h>
union Data {
int i; float f; char c;
};
void main() {
union Data values[3];
values[0].i = 10; values[1].f = 3.14; values[2].c = 'A';
for (int i = 0; i < 3; i++)
printf("Data[%d] - Integer: %d, Float: %.2f, Char: %c\n", i, values[i].i, values[i].f, values[i].c);
}
IX. UNIONS AND FUNCTIONS: In C programming, unions are used to define custom data types that
can hold multiple pieces of information of different types, but only one type at a time. Functions, on the
other hand, are blocks of code designed to perform specific tasks. Unions can be used with functions to
manipulate data more effectively.
1. Passing Unions to Functions: Unions can be passed to functions in two ways. In pass by value, a
copy of the union is passed, and changes made inside the function don’t affect the original union. In pass
by reference, a pointer to the union is passed, allowing the function to modify the original union
directly. Passing by reference is more efficient, especially for large unions, because it avoids copying the
data.
a) Pass by Value: When a union is passed by value, a copy of the union is passed to the function.
Any modifications made to the union inside the function will not affect the original union.
Example:
void modifyData(union Data d) {
d.i = 100; // Modifying the copy of the union
}
b) Pass by Reference: When a union is passed by reference (using pointers), the function can
directly modify the original union. This is more efficient than passing large unions by value
because it avoids unnecessary copying of data.
Example:
void modifyData(union Data *d) {
d->i = 100; // Modifying the original union using pointer
}
2. Returning Unions from Functions: In C, functions can return unions, allowing a function to create a
new union, populate it with data, and send it back to the caller. This is useful for returning complex or
modified data from a function. By returning unions, you can effectively manage and organize related
data types across different parts of the program.
Example:
#include <stdio.h>
union Data {
Bit Fields in Structures: When using bit fields in structures, you can define a structure that allocates
only a specified number of bits to each member, making it possible to store small pieces of data more
efficiently. This is especially useful in cases where each member represents a flag (like a true/false
value) or a small range of values.
Syntax:
struct structure_name {
data_type member_name : number_of_bits;
};
Bit Fields in Unions: Bit fields can also be used in unions, where the members share the same memory
location. In a union, all members share the same starting memory address, but with bit fields, you can
still allocate different amounts of memory for each member (in terms of bits), even though the actual
data will overlap in the union.
Syntax:
union union_name {
data_type member_name : number_of_bits;
};
#include <stdio.h>
enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
int main() {
enum Weekday today = Wednesday;
printf("Today is %d\n", today); // Output: 2
return 0;
}
We've declared an enum named Weekday. We've declared a variable today of type Weekday and
assigned it the value Wednesday. The printf statement prints the integer value associated with
Wednesday, which is 2. By using enums, we can make our code more readable and less error-prone, as
we can use meaningful names for integer constants instead of raw numbers.
TOPIC – 5
i) Text Mode: All the text streams consist of lines of characters (string of characters) and
each line is terminated by a combination of carriage return (CR) and linefeed {LF}. When Enter
ii) Binary Mode: No such types of translation take place. All characters are processed without
change. Binary files store floating point data more accurately and stored in compact way as
compared to the text files. In binary mode characters are stored and processed as in the main
memory.
ii) Opening a file: A file is opened by using fopen (),in-built high-level input/output function. The
general format for declaring and opening a file is as:
FILE *fp;
fp =fopen("filename", "mode");
Where FILE is the data structure and is the low level reserve word of C Language for the creating a
buffer area as discussed already. Here fp is the file pointer tells us beginning of the buffer area for
storing the data, filename is the name of the data file having less than eight characters, mode is the
way file is opening and there are three modes in opening the files. These are as follows:
1. w Open the file for writing only
2. r Open the file for reading only
3. a Open the file for appending only.
Note that when you use "w" mode, new file will be created, If the file is already created, then it
will overwrite the data. For example, some valid file opening statements are as:
FILE *pl, *p2, *p3;
P1 = fopen("Raja", "r"); /* file opened for reading the data from
"Raja" file p2 = fopen ("Sunny", "w"); /* file opened for wring the data
to "Sunny" file
p3 = fopen ("MONA", "a"); /* file opened to insert more data to "MONA" already created data file */
Note that some compiler use "r+", "w+" and "a+" mode, which have meaning as:
r+ : both for reading and writing. The stream will be position at the start of the file.
w+ : both for reading and writing. The stream will be created if it does not exist.
a+ : both for reading and appending. The stream will be position at the end of the file.
Files Program :
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("my_file.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "This is a line of text.\n");
fprintf(fp, "This is another line.\n");
fclose(fp);
fp = fopen("my_file.txt", "r");
if (fp == NULL) return 1;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}