Professional Documents
Culture Documents
CP Unit Vi
CP Unit Vi
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.
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.
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.
struct date
{
intdat;
intmonth;
intyear;
};
Thereisaone-to-onecorrespondencebetweenthemembersandtheirinitializing
values.
Cdoesnotallowtheinitializationofindividualstructurememberswithinthe
structure definition template.
struct date
{
intdat;
intmonth;
intyear;
};
2
UNIT-VI COMPUTER PROGRAMMING
Output
Student Na me: XYZ
Roll No: 581
Ge nder: M
Marks obtained:79.5
Address: Guntur
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.
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;
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
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
6
UNIT-VI COMPUTER PROGRAMMING
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.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.
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.
The fopen() function is used to open a file and associates an I/O stream with it. The
general form of fopen() is
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.
Mode Meaning
R Open a text file for reading only. If the file doesn‟t exist, it returns null.
w+ Opens the existing text file or Creates a text file for read/write
fclose(file pointer);
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.
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);
10