0% found this document useful (0 votes)
19 views19 pages

unit 4

for c beginners

Uploaded by

ggdsurya1845
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views19 pages

unit 4

for c beginners

Uploaded by

ggdsurya1845
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

UNIT-IV Structures, Unions, Bit Fields: Introduction, Nested Structures, Arrays of

Structures, Structures and Functions, Self-Referential Structures, Unions, Enumerated Data


Type —Enum variables, Using Typedef keyword, Bit Fields. Data Files: Introduction to Files,
Using Files in C, Reading from Text Files, Writing to Text Files, Random File Access

Q:Explain about Structures?


Structure in c is a user-defined data type that enables us to store the collection of different
data types. Each element of a structure is called a member..
Defining and Declaring Structures
To define a structure, we use the struct keyword followed by the structure name and the
members enclosed in curly braces.
the syntax to define the structure in c is as follows
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
struct employee
{
int id;
char name[20];
float salary;
};

struct Person {
char name[50];
int age;
float salary;
};

Unit 4 1
The following image shows the memory allocation of the structure employee that is
defined in the above example.

Here, struct is the keyword; employee is the name of the structure; id, name, and salary are
the members or fields of the structure. Let's understand it by the diagram given below:

example:
struct Person {
char name[50];
int age;
float salary;
};
In this example, Person is a structure with three members: name, age, and salary.

Unit 4 2
Creating Structure Variables
Once a structure is defined, you can create variables of that type. There are two ways to
declare structure variables:
1. With the structure template:
Syntax: struct name/tag
{
//structure members
} variables;
We can also declare many variables using comma (,) like below
Example:
struct Person
{
char name[50];
int age; float salary;
} person1, person2;
2. After the structure template:
Declaring structure variable using struct keyword.
Syntax: struct structurename variables;
Example: struct Person person1, person2;
Initializing Structure Members
We can initialize the structure by providing the values of the members in the list during the
declaration. The values in the list will be then assigned to the member of
the structure sequentially. It means the first value in the list will be assigned to the first
member and so on.Structure members can be initialized using an initializer list or
assignment operator. Here are examples:
1. Using Initializer List:
Syntax to Initialize Structures in C
structName varName = {value1, value2, value3 ..., valueN};
Example: struct Person person1 = {"RASHMITHA", 30, 60000.0};
2. Using Assignment Operator: use the dot operator we can initialize structure
variables

Unit 4 3
struct Person person1;
person1.age = 30;
Accessing Structure Members
We can access the members of a structure using the dot operator (.). It is also called
the member access operator.
For example:
person1.age = 30;
printf("Age: %d\n", person1.age);
Example:
#include<stdio.h>
struct car
{
char name[100];
float price;
};

void main()
{
struct car car1 ={"xyz", 987432.50};
printf("Name of car1 = %s\n",car1.name);
printf("Price of car1 = %f\n",car1.price);
}
Nested Structures
Nested structures in C involve defining one structure within another. This is useful for
organizing related data hierarchically. Below are various ways to use nested structures:
struct Person {
char name[50];
struct Address
{
char city[50];
int zip;
}a;
}p1;
You can access nested structure members using the dot operator:

Unit 4 4
Strcpy(p1.a.city,”rajam”);
p1.a.zip = 12345;
Example: Program using nested structure
#include <stdio.h>
#include<string.h>
struct Student {
int sno;
char name[50];
struct dob {
int dd;
int mm;
int yy;
} d; // Variable of the nested structure
}s1;
int main() {
s1.sno = 101;
strcpy(s1.name,"madhavi");
s1.d.dd = 29;
s1.d.mm = 10;
s1.d.yy = 87;
printf("Student Details:\n");
printf("Name: %s\n", s1.name);
printf("Roll Number: %d\n", s1.sno);
printf("DATE Of Bitrh:%d-%d-%d",s1.d.dd,s1.d.mm,s1.d.yy);
return 0;
}

Unit 4 5
Note: for the above structure we can also initialize
struct student s1={101,"madhu",{29,10,87}}; // initializer list
Array of structures
An array of structures allows you to store multiple instances of a structure in a single array.
This is useful when you need to handle multiple objects that share the same structure.
Example demonstrating an array of structures with student details:
#include <string.h>
struct Student {
int sno;
char name[50];
struct dob {
int dd;
int mm;
int yy;
} d;
};
int main() {
struct Student students[2] = { 101, "Madhavi", {29, 10, 87}}, {102, "abc", {15, 6, 90}} };
for (int i = 0; i < 2; i++) {
printf("Student %d Details:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].sno);
printf("Date of Birth: %d-%d-%d\n", students[i].d.dd, students[i].d.mm,
students[i].d.yy);
} return 0; }

Unit 4 6
structures and functions
We can use structures with functions in C to modularize our code. Functions can take
structures as arguments, return structures, or manipulate the data within them.
#include <stdio.h>
struct Rectangle {
float length;
float width;
};
float calculateArea(struct Rectangle r)
{
return r.length * r.width;
}
int main() {
struct Rectangle rect1 = {5.0, 3.0};
float area = calculateArea(rect1);
printf("Area of the rectangle: %.2f\n", area);
return 0; }
A self-referential structure is a structure that contains a pointer to an instance of itself. In
other words, it is a structure that has a member which points to another structure of the
same type.
Self-referential structures are often used in the implementation of linked lists, trees, or
graphs. These structures are useful when you want to create data structures where each
element needs to point to the next element of the same type.
struct Node {
int data;
struct Node* next; // Pointer to the next node (self-referential)
};
Note:In the struct Node, the next pointer is a pointer to another Node structure. This makes
the structure self-referential.
Structure Pointers
You can create pointers to structures and access members using the arrow operator (->).
For example:
struct Person *ptr = &person1;
ptr->age = 30;

Unit 4 7
Explain about C – Union?
• C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.
• Union and structure in C are same in concepts, except allocating memory for their
members.
• Structure allocates storage space for all its members separately.
• Whereas, Union allocates one common storage space for all its members
• We can access only one member of union at a time. We can’t access all member values
at the same time in union. But, structure can access all member values at the same time.
This is because Union allocates one common storage space for all its members.
Whereas Structure allocates storage space for all its members separately.
• Many union variables can be created in a program and memory will be allocated for
each union variable separately.
Declare a union:
Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
union student
{
int mark;
char name[10];
float average;
};
Declaring union variable: union student report;
Initializing union variable: union student report = {100, “Mani”, 99.5};
Accessing union members:
report.mark;
report.name;
report.average;

Unit 4 8
Example program for C union:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
}

Unit 4 9
Difference between structure and union in C:
S.no C Structure C Union
1 Structure allocates storage Union allocates one common storage space for all its
space for all its members members.
separately. Union finds that which of its member needs high
storage space over other members and allocates that
much space
2 Structure occupies higher Union occupies lower memory space over structure.
memory space.
3 We can access all members We can access only one member of union at a time.
of structure at a time.
4 Structure example: Union example:
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };
5 For above structure, For above union, only 8 bytes of memory will be
memory allocation will be allocated since double data type will occupy
like below. maximum space of memory over other data types.
int mark – 2B Total memory allocation = 8 Bytes
char name[6] – 6B
double average – 8B
Total memory allocation =
2+6+8 = 16 Bytes

Q: Explain about Enumeration data type in C?


Enumerated Data Type (enum):
• An enumerated data type in C is a user-defined data type that consists of named integer
constants. It provides more readable code and makes it easier to manage sets of related
constants.
• It consists of named integer constants as a list.It start with zero by default and value is
incremented by 1 for the sequential identifiers in the list.
Syntax : enum identifier
{
enumerator-list
};

Unit 4 10
Enum Variables and Their Values:
enum variables are used to store values of an enumerated type.By default, the first value of
an enum is assigned the value 0, and each subsequent value is incremented by 1. We can
manually set specific values if needed. enum variables are used to store values of an
enumerated type

enum EnumName {
Constant1, // 0 by default
Constant2, // 1 by default
Constant3 // 2 by default
};

We can also explicitly assign values to the constants:


enum EnumName {
Constant1 = 1, // Manually set the value
Constant2 = 5, // Manually set the value
Constant3 = 10 // Manually set the value
};

#include <stdio.h>

enum Weekdays { Sunday = 1,Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

int main() {
enum Weekdays today;
today = Wednesday;
printf("Today is day number %d\n", today);
return 0;
}

Output:

The variable today is of type enum Weekdays and can hold one of the values from the
Weekdays enumeration.

Unit 4 11
Q: Explain about Typedef?

The typedef keyword is used to create a new type name (alias) for an existing data type. You
can combine typedef with enum,structure,union to give a custom name to your enum type,
making the code more concise and easier to read.

Syntax:typedef for enum

typedef enum
{
Constant1,
Constant2,
Constant3
}NewEnumName;

Typedef for Structures


The typedef keyword can be used to create an alias for a structure, simplifying the syntax.
For example:
typedef struct
{
char name[50];
int age;
} Person;
Person person1;

Q:Explain about Bit Fields?


Bit fields allow you to specify the exact number of bits a structure field will occupy. This can
help conserve memory when you need to store values that don't require the full size of the
data type.
Syntax:
struct StructureName {
type variable_name : number_of_bits;
};
struct Employee {
unsigned int id : 10; // 10 bits for employee ID (0 to 1023)
unsigned int age : 7; // 7 bits for age (0 to 127)
};

Unit 4 12
unsigned int is used in bit fields when you want to store only non-negative values, and you
want to make full use of the available bits. Signed int covers range -512 to +511
struct Employee {
signed int id : 10; // 10 bits for employee ID (-512 to 511)
signed int age : 7; // 7 bits for age (-64 to 63)
};
#include <stdio.h>
struct Flags {
unsigned int isActive : 1; // 1 bit for active status (0 or 1)
unsigned int isAdmin : 1; // 1 bit for admin status (0 or 1)
};
int main() {
struct Flags flags;
flags.isActive = 1; // Active
flags.isAdmin = 0; // Not Admin
printf("Is Active: %u\n", flags.isActive);
printf("Is Admin: %u\n", flags.isAdmin);
return 0; }

Unit 4 13
Q:Explain about Files ?
In C language the functions scanf( ) and printf( ) are used to read
and write data. These are console oriented input and output functions which always use the
terminal (keyboard and screen) as the target place. These functions works fine as long as the
data is small. However in many real-life problem situations involves large – volume of data. In
such situations, the console oriented Input Output operations raises two problems.
1) When a program is terminated, the entire data is lost.
2) If you have to enter large number of data,it will take a lot of time to enter them all.

Solution with files for the above problems is:


A File is place on your physical disk where a group of related data is stored.
1) Storing data in a file will preserve your data even if the program terminates.
2) If you have a file containing all the data, you can easily access the contents of the file
using few commands in c.
3) You can easily move your data from one computer to another without any changes.

TYPES OF FILES:
When dealing with files, there are two types of files you should know about.
1) Text files
2) Binary files
1) Text Files: Text files are normal .txt files that you can easily create using notepad
or any simple text editors. When you open those text files, you will see all the contents
with in the files as plain text. You can easily create using notepad or simple text editors.
They take minimum effort to maintain are easily readable, and provide least security
and takes bigger storage space.
2) Binary Files: Binary files are mostly the .bin files in your computer. Instead of
storing data in plain text, they store it in the binary form(0’s and 1’s). they can hold
higher amount of data, or not readable easily and provides a better security than text
files.

USING THE FILES IN C LANGUAGE:


A file is a place on the disk where a group of related data is stored. When working with
files, we need to declare a pointer of type file. This declaration is needed for communication
between the file and program.\
In c, you can perform 6 major operations on the file either it may be text or binary files.
1) Creation of new file
2) Opening an existing file.
3) Reading from a file.
4) Writing to a file.
5) Moving to a specific location in a file.
6) Closing a file.

Unit 4 14
FILE HANDLING FUNCTIONS IN C:
o File is created for permanent storage of data. It is readymade structure.
o In C language, we use a structure pointer of the file type to declare a file.
FILE *FP;
o There are two distinct ways to perform file operations in C.
o The first one is known as the low-level I/O and uses UNIX system calls.
o The second method is referred to as the high-level I/O operation and uses
functions in C’s standard I/O library.
The important high level I/O file handling functions that are available in the stdio.h
library are.

FUNCTION DESCRIPTION
fopen( ) Creates new file or open an existing file
fclose( ) Closes a file which has been opened for use
getc ( ) Reads a character from a file
putc( ) Writes a character to a file
fscanf ( ) Reads a set of data to a file
fprintf ( ) Writes a set of data to a file
fgets() Read string of character from a file
fputs() Write string of character from a file
ftell() Gives current position in the file
feof() Detects end of file marker in the file.

In C language processing of a file includes the following steps.


➢ Declare a file pointer variable by using FILE data structure.
➢ Open a file using fopen() function
➢ Process the file using suitable function.
➢ Close the file using fclose() function.

CREATING OR OPENING A FILE:-

Before you can Read/Write information from (to) a file on a disk we must open a file. To open
a file we have called a function fopen().

Unit 4 15
General syntax for open a file

FILE *fp;
fp=fopen(“filename”,”mode”);

The first statement declares the variables fp as a”pointer to the data type file”.
In the second statement “file name” is the name of the name of the file to be opened
and “mode” specifies the purpose of opening the file.
modes in standard I/O can be of following types.

File mode Description of mode During inexistence of file


r Open for reading If the files doesnotexist,fopen() return
NULL
w Open for writing If the file exists,its contents are
overwritten. If the file doesnotxist,it
will be create.
a Open for append. i.e, data If the file does not exist it will be
is added to the end of the created.
file
r+ Open for both reading and If the file doesnot exist fopen() returns
writing NULL
w+ Open for both reading and If the file exists,it contents are over
writing written. If the file doesnot exist it will
be created.
a+ Open for both reading and If the file doesnot exist it will be
appending created.

The above file modes are used for text files only. If you are going to handling binary
files, then you will use following access mode rb, wb, ab, rb+, wb+, ab+
Example: #include<stdio.h>
int main( )
{
FILE *fp;
fp=open(“sample.txt”,”w”);
return 0;
}
CLOSING A FILE:
The file should be closed after reading or writing. This ensures that all out standing
information associated with the file is flushed out from the buffers and all links to the file are
broken. The fclose() function is used to close an already opened file.

Unit 4 16
Syntax: fclose(file-pointer);
This would close the file associated with the file pointer ‘fptr’.

Example: #include<stdio.h>
int main( )
{
FILE *fp;
fp=fopen(“sample.txt”, “w”);
fclose(fp);
return 0;
}
Here fclose( ) function closes the file and returns ‘zero’ on success, or ‘EOF’ if there is
an error in closing the file.
Writing to a file

To write the file, we must open the file in a mode that supports writing.

For example, if you open a file in “w” mode, you will be able to write the file

FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");

Reading a File

To read the file, we must open it first using any of the mode,

for example if you only want to read the file then open it in “r” mode.

/* Opening a file in r mode*/


fp1= fopen ("C:\\myfiles\\newfile.txt", "r");

DELETING FILE:
The C library function remove deletes the given filename so that it is no longer
accessible.
Syntax: int remove (const char*filename);
Here file name is the c string containing the name of the file to be deleted. This
function returns zero on successful deletion of file and returns -1 on error and errno is set
approximately.

Unit 4 17
RENAMING A FILE:
In the C programming language, the rename function changes the name of a file. You
must close the file before renaming, as a file cannot be renamed if it is open.
Syntax: int rename(const char *old_filename, const char *new_file name);

Q: Explain about Random Access File?


C language's random access file enable us to read or write any data in the disk file without
first reading or writing all the data that came before it. We can easily look for data in a random-
access file, edit it, or even delete it. Random access files can be opened and closed using the
same opening way as sequential files in C programming. Random access to a file can be carried
out in C with the aid of functions like ftell(), fseek(), and rewind().

Types of Access files


The following methods exist in C for accessing data that is saved in a file:

• Sequential Access
• Random Access
Sequential Access
Sequential access is not the optimum method for reading the data in the centre of the file if
the file size is too large. A sequential file is a kind of file organization in which we can keep the
data continuously, and every record is stored after the other and can be accessed the data
sequentially. In this file, the data is read from the start of the file and processed in the
sequence it comes in the file. It is mainly suitable for those applications where the data is
processed sequentially and doesn't access randomly.
Random Access
A random access file in C is a kind of file that enables us to write or read any data in the disk
file without having to read or write each section of data before it. In this file, we may instantly
find for data, modify it, or even delete or remove it. We may open and close random access
files in C in the same way we can sequential files, but we require a few more functions

Functions of Random Access file


there are mainly three functions that assist in accessing the random access file in C:
• ftell()
• rewind()
• fseek()
ftell ( )
It returns the current position of the file ptr. ftell ( ) is used for counting the number of
characters which are entered into a file.
The syntax is as follows −
int n = ftell (file pointer);

Unit 4 18
rewind ( )
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);

fseek ( )
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
Offset
• The no of positions to be moved while reading or writing.
• If can be either negative (or) positive.
o Positive - forward direction.
o Negative – backward direction.
Position
It can have three values, which are as follows −
• 0 – Beginning of the file.
• 1 – Current position.
• 2 – End of the file.

Unit 4 19

You might also like