Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

UNIT-VI COMPUTER PROGRAMMING

6.0 Introduction
A simple variable can store one value at a time. An array can store a number of
variables of the same type. For example, marks obtained by a student in five subjects can
be stored in an array marks[5]. marks[0], marks[1], etc, will store student information
like the marks obtained in various subjects. Suppose we want to store student
information in array name, htno, address, marks obtained. We cannot store this
information in an array because name, htno, address are of character type and marks
obtained is of integer type. So arrays are used to store homogeneous data. To store
heterogeneous data elements in a single group, C language provides a facility called the
structure.

6.1 Definition of structure


A structure is a collection of variables of different types that are logic ally grouped together
and referred under a single name.
 Structure is a user-defined data type.
 User-defined datatype also called as derived datatype why because we derived it
from the primary/basic data types.

In C language, a structure can be defined as follows:

struct structure_name
{
data_type member_variable1;
data_type member_variable2;
… …
data_type member_variableN;
};

The variables declared inside the structure are known as members of the structure.

For Example
struct student
{
charname[20];
char ht_no[10];
char gender;
float marks;
long int phone_no;
};

Points remember
 The members of the structure may be any of the common data type, pointers,
arrays or even the other structures.
 Member names within a structure must be different.
 Structure definition starts with the open brace({)and ends with closing brace(})
followed by a semicolon.
 The compiler does not reserve memory any memory when structure is defined.
We have to define the variable to store its information.

6.2 Structure variable


As stated earlier, the compiler does not reserve memory any memory when structure is
defined. To store members of structures in memory, we have to define the structure
variables. The structure variables may be declared in the following ways:
 In the structure declaration
 Using the structure tag

In the structure declaration


The structure variable can be declared after the closing brace. Following example shows
this.

1
UNIT-VI COMPUTER PROGRAMMING
struct date
{
Int dat;
int month;
int year;
}dob, doj;

He re date is the structure tag, while dob and doj are variables type date.

Using the structure tag


The variables of structure may also be declared separately by using the structure tag as
shown below:

struct date
{
intdat;
intmonth;
intyear;
};

struct date dob, doj;

6.3 Initialization of structure


We can initialize the values to the members of the structure as:

struct structure_name structure_variable={value1, value2, … , value N};

 Thereisaone-to-onecorrespondencebetweenthemembersandtheirinitializing
values.
 Cdoesnotallowtheinitializationofindividualstructurememberswithinthe
structure definition template.
struct date
{
intdat;
intmonth;
intyear;
};

struct date dob={25,12,1998};

Following example shows how to initialize structure in the above method.


#include <stdio.h>
struct student
{
Char name[30];
int htno;
char gender;
int marks;
char address[30];
};
Int main()
{
struct student st={"XYZ",581,'M',79.5,"Guntur"};
printf("StudentName:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Gender:%c \n",st.gender);
printf("Marksobtained:%d\n",st.marks);
printf("Address:%s\n",st.address);
return0;
}

2
UNIT-VI COMPUTER PROGRAMMING

Output
Student Na me: XYZ
Roll No: 581
Ge nder: M
Marks obtained:79.5
Address: Guntur

6.4 Accessing members of structure


For accessing any member of the structure, we use dot (.) operator or period operator.

Syntax:

structure_variable.member name

Here, structure_variable refers to the name of a structure type variable and member
Refers to the name of a member within the structure.

Following example shows how to access structure members


#include <stdio.h>
struct date
{
int day;
int month;
int year;
};

Int main()
{
struct datedob;
printf("Enter your birthday details\n");
printf("Enter the day:");
scanf("%d", &dob.day);
printf("Enter themonth:");
scanf("%d",&dob.month);
printf("Enter the year:");
scanf("%d",&dob.year);
printf("Your date of birth is:");
printf("%d-%d-%d\n",dob.day,dob. month,dob.year);
return 0;
}

Output
Enter your birthday details
Enter the day:12
Enter the month:7
Enter the year:1998
Your date of birth is: 12-7-1998

6.5 NestedStructure
We c an take any structure as a member of structure. i.e. called structure with in
structure or nested structure.
For example:
struct
{
member 1;
member 2;
……
……
struct
{

3
UNIT-VI COMPUTER PROGRAMMING
member 1;
member 2;
}s_var2;
……
member m;
}s_var1;

For accessing the member 1 of inner structure we write as:


s_var1.s_var2. member1;

Following example illustrates the nested structure


#include <stdio.h>
struct student
{
Char name[30];
int htno;
struct date
{
int day;
int month;
int year;
}dob;
char address[10];
};
Int main()
{
struct student st;
printf("Enter student details\n");
printf("Enter student na me:"); scanf("%s ",st.na me);
printf("Enter rollno:"); scanf("%d", &st.htno);
printf("Enter address:"); scanf("%s ",st.address);
printf("Enter the day:"); scanf("%d",&st.dob.day);
printf("Enter themonth:"); scanf("%d",&st.dob.month);
printf("Enter the year:"); scanf("%d", &st.dob.year);
printf("Student Details\n------------------- \n");
printf("StudentName:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Date of birth:%d-%d-%d\n",st.dob.day,st.dob.month,st.dob.year);
printf("Address:%s\n",st.address);
return 0;
}

Output
Enter student details
Enter student name: Vijayanand
Enter roll no: 511
Enter address: Guntur
Enter the day:12
Enter the month: 7
Enter the year:1998
Student Details
-----------------
Student Na me: Vijay
Roll No: 511
Date of birth is: 12-7-1998
Address: Guntur

6.6 Self-referential structure


A self-referential is one which contains a pointer to its own type. This type of structureis
also known as linked list. For example

4
UNIT-VI COMPUTER PROGRAMMING

struct node
{
int data;
struct node *nextptr;
};

Definesadatatype,structnode.Astructuretypestructnodehastwomembers-integer
memberdataandpointermembernextptr.Membernextptrpointstoastructureoftype
structnode–astructureofthesametypeasonebeingdeclaredhere,hencetheterm“self-
referentialstructure”.Membernextptrreferredtoasalinki.e.nextptrcanbeusedtototie a
structure of type struct node to another structure of the same type. Select referential
structures can be linked together to form a usual data structures such as lists etc.

#include <stdio.h>
struct student
{
Char name[30];
int age;
char address[20];
struct student *next;
};

Int main()
{
struct student st1={"Raja",20,"Guntur"};
structstudentst2={"Raghu",21,"Narasaraopet"};
structstudentst3={"Nagaraju",22,"Sattenapali"};
st1.next=&st2;
st2.next= &st3;
st3.next=NULL;
printf("StudentName:%s\tAge:%d\tAddress:%s\n",st1.name,st1.age,st1.address);
printf("Student 1 stored at %x \n",st1.next);
printf("StudentName:%s\tAge:%d\tAddress:%s\n",st2.name,st2.age,st2.address);
printf("Student 2 stored at %x \n",st2.next);
printf("Student Na me:%s\tAge:%d\tAddress:%s\n",st3.na me,st3.age,st3.address);
printf("Student 3 stored at %x \n",st3.next);
return 0;
}
Output
Student Name:Raja Age:20
Address:GunturStudent 1
stored at88f0
Student Name:Raghu Age:21
Address:NarasaraopetStudent 2
stored at8854
StudentName:NagarajuAge:22 Address:Sattenapalli
Student 3 stored at 0

6.7 Union
A Union is a user defined data type like structure. The union groups logically related
variables into a single unit.
 In structure each member has its own memory locationwhere as the members of
union has the same memory location.
 We c an assign values to only one member at a time, so assigning value to
another member that time has no meaning.

When a union is declared, compiler allocates memory locations to hold largest data type
member in the union. So, union is used to save memory. Union is useful when it is not
necessary to assign the values to all the members of the union at a time.

5
UNIT-VI COMPUTER PROGRAMMING
Union can be declared as
union
{
member 1;
member 2;
……
……
member N;
};

Following example shows how to declare union and accessing the members of union

#include<stdio.h>
union student
{
Char name[30];
int age;
};
Int main()
{
union student st;
clrscr();
printf("Enter student name:");
scanf("%s ",st.na me);
printf("StudentName:%s, age= %d\n",st.name,st.age);
st.age=20;
printf("StudentName:%s, age= %d\n",st.name,st.age);
getc h();
return 0;
}

Output
Enter student name: Vijay
Student Na me: Vijay,age= 26966
Student Na me: ¶ , age= 20

Look at the output


First time union member name has a value which is inputted through the keyboard. So
name is displayed. Ne xttime we wereassigned a values to age, union will lost thevalue in
member name, so this time only student‟s age is displayed.

Following figure illustrates how me mbersof structure and unionare stored.


struct student
{
Char name[15];
int age;
};

Fig. Storage in structure


union student
{
charname[15];
intage;
};

6
UNIT-VI COMPUTER PROGRAMMING

Fig. Storage in union

6.8 Comparison between structure and union

S. No Structure Union
1. Stores heterogeneous data Stores heterogeneous data
2. Members are stored separately in Members a restored in same memory
memory locations. location.
3. In structures all the members are In union only one member is available
available. at a time.
4. Occupies more memory when Occupies less memory when compared
compared to union with structure.
5. Size of the structure is the total Size of the union is the size of the
Memory space required by its members Largest data type member in the union.

6.9 Comparison between array and structure


S. No Array Structure
1. Stores homogeneous data Stores heterogeneous data
2. Two arrays of same type cannot be Structures of same type can be
assigned to one to one assigned.
3. Arrays can be initialized Structures cannot be initialized
4. Array is a combination of elements Structure is a combination of members
5. Multidimensional arrays are possible No incase of structures
6. No operators are required to access Operators like „.‟ or „->‟a re require d to
elements of an array access members of a structure.
7. An element in the array referenced by Members in a structure will be
Specifying array name and its position referenced as
in the array. For example: a[5] Structure name .member name
8. C treats array names as pointers Structure name is not treated as
Pointer variable.
9. When an array name is passed as When an structure name is passed as
argument to function, it is c all by argument to function, it is call by value.
reference.

6.10 FILES
File is a collection of bytes that is stored on secondary storage devices like hard disk. There
are two kinds of files in a system. They are,
1. ASCII Text Files
2. Binary Files

A file has a beginning and an end ; It has a current position, typically defined as on many
bytes from the beginning. You can move the current position to any other point in file. A
new current position can be specified as an offset from the beginning the file.

Types of files
ASCII Text Files
 A text file can be a stream of characters that a computer can processs equentially.
 It is processed only in forward direction.

7
UNIT-VI COMPUTER PROGRAMMING
 It is opened for one kind of operation (reading, writing, or appending) at any give
time.
 It can read only one character at a time.
Binary Files
 A binary file is collection of bytes.
 In „C‟ both a byte and a character are equivalent.
 A binary file is also referred to as a character stream, but there are two essential
differences.

6.11 File streams


A stream is a series of bytes of data flow from your program to a file or vice-
versa. A stream is an abstract representation of any external source or destination for
data, so the keyword, the command line on your display and files on disk are all
examples of stream. „C‟ provides numbers of function for reading and writing to or from
the streams on any external devices. There are two formats of streams which are as
follows:
1. Text Stream
2. Binary Stream

Text Stream
 It consists of sequence of characters, depending on the compilers.
 Eachcharacterlineinatextstreammaybeterminatedbyanewlinecharacter.
 Text streams are used for textual data, which has a consistent appearance from
one environment to another or from one machine to another.

Binary Stream
 It is a series of bytes.
 Binarystreamsareprimarilyusedfornon-textualdata,whichisrequiredtokeep exact
contents of the file.

6.12 File Operations


In C, you can perform four major operations on the file, either text or binary:
1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file

6.12.1 1 Opening a file


To perform any operation (read or write), the file has to be brought into memory
from the storage device. Thus, bringing the copy of file from disk to memory is called
opening the file.

The fopen() function is used to open a file and associates an I/O stream with it. The
general form of fopen() is

fopen(const char *filename, const char *mode);

This function takes two arguments. The first argument is the name of the file to be opened
while the second argument is the mode in which the file is to be opened.

NOTE: Before opening a file, we have to create a file pointer that is created using FILE
Structure is defined in the “stdio.h” header file.

For example
FILE *fp;
//fp=fopen(“myfile.txt”,”r”);
//if(fp==NULL)
if(fp = fopen(“myfile.txt”,”r”)) ==NULL)
{
printf(“Error opening a file”);

8
UNIT-VI COMPUTER PROGRAMMING
exit(1);

9
UNIT-VI COMPUTER PROGRAMMING
}
This opens a file named myfile.txt in read mode.

File opening modes

Mode Meaning

R Open a text file for reading only. If the file doesn‟t exist, it returns null.

 Opens a file for writing only.


 If file exists, then all the contents of that file are destroyed and new
W fresh blank file is copied on the disk and memory with same name.
 If file doesn‟t exists, a new blank file is created and opened for writing.
 Returns NULL if it is unable to open the file
 Appends to the existing text file.
 Adds data at the end of the file.
A
 If file doesn‟t exists then a new file is created.
 Returns NULL if it is unable to open the file.

Rb Open a binary file for reading

Wb Open a binary file for reading

Ab Append to abinary file

r+ Open a text file for read/write

w+ Opens the existing text file or Creates a text file for read/write

r+b Open a binary file for read/write

w+b Create abinary file for read/write

a+b Append a binary file for read/write

6.12.2 2 Closing a file


To close a file and dis-associateit with a stream, use fclose() function. It returns zero if
successful else returns EOF if error oc c urs. The fc loseall() c loses all the files opened
previously. The general form is:

fclose(file pointer);

6.12.3 3 Reading a file


When we want to read contents from existing file, then we require opening that file into
read mode that means “r” mode. To read file follow the below steps

1. Initialize the file variable


2. Open a file in read mode
3. Accept information from file
4. Write it into the output devices
5. Close the file
Example
#include<stdio.h>
void main()
{
FILE *fp;

1
0
UNIT-VI COMPUTER PROGRAMMING
char ch;
clrscr();
fp=fopen("test.txt","r"); // file opened in read mode
if(fp==NULL)
{
printf("Unableto open test.txt");
}
else
{
do
{ ch = getc(fp);
putchar(ch);
}while(c h!=EOF);
fc lose(fp);
}
getch();
}
`

Output
Welcome to Files. You opened a file name test.txt
Note: EOF mea ns End of File that denotes the end-of-file.

6.12.4 4 Writing to the file


When we want to write new data to the file, then we require opening that file in write
mode that means “w” mode. To write in to the file follow the below steps

1. Initialize the file variable


2. Open a file in write mode
3. Accept information from the user
4. Write in to the file
5. Close the file

Example
#include<stdio.h>
Void main()
{
FILE *fp;
char ch;
fp= fopen("test.txt","w"); //fileopenedinwritemode
printf("EnteryourInput\n");
while((ch=getchar())!=EOF) //writing data to thefile
{
putc(ch,fp) ;
}

fclose(fp);

printf("\nYou have entered\n");


fp= fopen("test.txt","r");
while((ch=getc(fp))!=EOF) //reading data from file
printf("%c",ch);
fc lose(fp);
}
Output
Enter your Input
Hi Students…! How are you?
All the best for your end exams.(press C TRL+Z for stopping)

You have entered


Hi Students…! How are you?
All the best for your end exams.

10

You might also like