CP UNIT VI R16

advertisement
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 f ive 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 De finition of structure
A structure is a collection of variables of different types that are logically grouped
together and referred under a single name.
 Structure is a user-defined data type.
 User-defined data type also called as derived data type 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
{
char name[20];
char ht_no[10];
char gender;
float marks;
long int phone_no;
};
Points remembe r
 The members of the structure may be any of the common data type, pointers,
arrays or even the other structures.
 Member names with in a structure must be different.


Structure definition starts with the open brace( {) and ends w ith 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 follow ing ways:
 In the structure declaration
 Using the structure tag
In the structure dec laration
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;
Here 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
{
int dat;
int month;
int year;
};
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, … , valueN};
There is a one-to-one correspondence between the members and their initializing
values.
 C does not allow the initialization of individual structure members w ithin the
structure definition template.
struct date
{
int dat;
int month;
int year;
};

struct date dob={25,12,1998};
Follow ing 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("Student Name:%s\n",st.name);
printf("Roll No:%d\n",st.htno);
printf("Gender:%c \n",st.gender);
printf("Marks obtained:%d\n",st.marks);
printf("Address:%s\n",st.address);
return 0;
}
2
UNIT-VI
COMPUTER PROGRAMMING
Output
Student Name: XYZ
Roll No: 581
Gender: M
Marks obtained:79.5
Address: Guntur
6.4 Accessing membe rs of structure
For accessing any member of the structure, we use dot (.) operator or period operator.
Syntax:
structure_variable . membername
Here, structure_variable refers to the name of a structure type variable and member
refers to the name of a member within the structure.
Follow ing example shows how to access structure members
#include<stdio.h>
struct date
{
int day;
int month;
int year;
};
int main()
{
struct date dob;
printf("Enter your birthday details\n");
printf("Enter the day:");
scanf("%d",&dob.day);
printf("Enter the month:");
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 Nested Structure
We can 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;
Follow ing 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 name:"); scanf("%s",st.name);
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 the month:"); scanf("%d",&st.dob.month);
printf("Enter the year:"); scanf("%d",&st.dob.year);
printf("Student Details\n------------------- \n");
printf("Student Name:%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 Name: Vijay
Roll No: 511
Date of birth is: 12-7-1998
Address: Guntur
6.6 Self-refe rential structure
A self-referential is one which contains a pointer to its own type. This type of structure is
also known as linked list. For example
4
UNIT-VI
COMPUTER PROGRAMMING
struct node
{
int data;
struct node *nextptr;
};
Def ines a data type, struct node. A structure type struct node has two members-integer
member data and pointer member nextptr. Member nextptr points to a structure of type
struct node – a structure of the same type as one being declared here, hence the term
“self-referential structure”. Member nextptr referred to as a link i.e. nextptr can be used
to to tie a structure of type struct node to another structure of the same type. select
referential structures can be linked together to forn 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"};
struct student st2={"Raghu",21,"Narasarao pet "};
struct student st3={"Nagaraju",22,"Sattenapali"};
st1.next = &st2;
st2.next = &st3;
st3.next = NULL;
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st1.name,st1.age,st1.address);
printf("Student 1 stored at %x \n",st1.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st2.name,st2.age,st2.address);
printf("Student 2 stored at %x \n",st2.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st3.name,st3.age,st3.address);
printf("Student 3 stored at %x \n",st3.next);
return 0;
}
Output
Student Name:Raja
Age:20
Address: Guntur
Student 1 stored at 88f0
Student Name:Raghu
Age:21
Address: Narasarao pet
Student 2 stored at 8854
Student Name:Nagaraju
Age: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 location where as the members
of union has the same memory location.
 We can 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;
};
Follow ing 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.name);
printf("Student Name:%s, age= %d\n",st.name,st.age);
st.age=20;
printf("Student Name:%s, age= %d\n",st.name,st.age);
getch();
return 0;
}
Output
Enter student name: Vijay
Student Name: Vijay, age= 26966
Student Name: ¶ , age= 20
Look at the output
First time union member name has a value which is inputted through the keyboard. So
name is displayed. Next time we were assigned a values to age, union w ill lost the value
in member name, so this time only student‟s age is displayed.
Follow ing figure illustrates how members of structure and union are stored.
struct student
{
char name[15];
int age;
};
Fig. Storage in structure
union student
{
char name[15];
int age;
};
6
UNIT-VI
COMPUTER PROGRAMMING
Fig. Storage in union
6.8 Comparison between structure and union
S.No
1.
2.
3.
4.
5.
Structure
Stores heterogeneous data
Members are stored separately in
memory locations.
In structures all the members are
available.
Occupies
more
memory
when
compared to union
Size of the structure is the total
memory space required by its members
Union
Stores heterogeneous data
Members are stored in same memory
location.
In union only one member is available
at a time.
Occupies less memory when compared
with structure.
Size of the union is the size of the
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 in case of structures
6.
No operators are required to access Operators like „.‟ or „->‟ are required 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]
structurename.membername
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 call by argument to function, it is call by value.
reference.
6.10 F ILES
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 def ined 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
ASC II Text Files
 A text file can be a stream of charact ers that a computer can process
sequentially.
 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 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 viceversa. 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 w riting t o 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.
 Each character line in a text stream may be terminated by a newline character.
 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.
 Binary streams are primarily used for non-textual data, which is required to keep
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 Opening a file
To perform any operation (read or w rite), the file has to be brought into memory
from the storage device. Thus, bringing the copy of file f rom disk to memory is called
opening the file.
The fopen() function is used to open a file and associates an I/O stream w ith 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;
if(fp = fopen(“myf ile.txt”,”r”)) == NULL)
{
printf(“Error opening a file”);
exit(1);
8
UNIT-VI
COMPUTER PROGRAMMING
}
This opens a file named myfile.txt in read mode.
File opening modes
Mode
r
Meaning
Open a text file for reading only. If the file doesn‟t exist, it returns null.


w
a






Opens a file for writing only.
If file exists, then all the contents of that file are destroyed and new
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 w riting.
Returns NULL if it is unable to open the file
Appends to the existing text file.
Adds data at the end of the file.
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 a binary file
r+
Open a text file for read/w rite
w+
Opens the existing text file or Creates a text file for read/write
r+b
Open a binary file for read/w rite
w +b
Create a binary file for read/w rite
a+b
Append a binary file for read/w rite
6.12. 2 Closing a file
To close a file and dis-associate it with a stream, use fclose() function. It returns zero if
successful else returns EOF if error occurs. The fcloseall() closes all the files opened
previously. The general form is:
fclose(file pointe r);
6.12. 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>
int main()
{
FILE *fp;
9
UNIT-VI
COMPUTER PROGRAMMING
char ch;
clrscr();
fp=fopen("f ile1.c","r");
// file opened in read mode
if(fp==NULL)
printf("Unable to open test.txt");
else
{
do
{
ch = getc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
getch();
return 0;
}
Output
Welcome to Files. You opened a file name test.txt
Note: EOF means End of F ile that denotes the end-of-file.
6.12. 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.
2.
3.
4.
5.
Initialize the file variable
Open a file in w rite mode
Accept information from the user
Write in to the file
Close the file
Example
#include <stdio.h>
int main()
{
FILE *fp;
char c;
fp = fopen("test.txt", "w ");
printf("Enter your Input\n");
while((c =getchar()) != EOF)
putc(c,fp);
fclose(fp);
printf("\nYou have entered\n");
fp = fopen("test.txt","r");
while((c =getc(fp)) != EOF)
printf("%c ",c);
fclose(fp);
return 0;
// file opened in w rite mode
//writing data to the file
//reading data from file
}
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
Download
Related flashcards
Create flashcards