unit-5
unit-5
1. Structure?
Ans:
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. Structures can simulate the use of classes and templates as it can
store various information
Create a Structure
Syntax:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
example
struct Student
{
char name[50];
int class;
int roll_no;
};
Declaring structure variable
We can declare a variable for the structure so that we can access the member of the
structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be declared
within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() functio
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Which approach is good
If number of variables are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable
in main() function.
Let's see the code to access the id member of p1 variable by. (member) operator.
p1.id
example of structure
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "ramu");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : ramu
example 2
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.salary=56000;
struct parant
{
data member 1;
data member 2;
};
struct student{
data member 1;
data member 2;
struct parant;
};
Embedded structure
this method is used to embed one structure inside another, i.e., defining one structure in the
definition of another structure. Thus using this method, the nested structure will be declared inside
the parent structure.
struct Parent
{
data member 1;
data member 2;
struct student
{
data member 3;
data member 4;
}stu1;
}parant1;
program:1
#include <stdio.h>
#include <string.h>
struct parant
{
char name[20];
struct student
{
char name[20];
int id;
}stu1;
}parant1;
int main( )
{
//storing employee information
strcpy(parant1.name, "ramu");//copying string into char array
strcpy(parant1.stu1.name, "raju");
parant1.stu1.id=301;
3. Array of Structures
Ans:
An array of structure in C programming is a collection of different datatype variables,
grouped together under a single name.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
4.
5. Structure Pointer or
structure and pointer or
structure to pointer
Ans:
he structure pointer points to the address of a memory block where the Structure is
being stored.
we use a structure pointer which tells the address of a structure in memory by
pointing pointer variable ptr to the structure variable.
Declare a Structure Pointer
we use the asterisk (*) symbol before the variable's name.
int main()
{
struct name *ptr, variablename;
}
Initialization of the Structure Pointer
ptr = &structure_variable;
We can also initialize a Structure Pointer directly during the declaration of a pointer.
struct structure_name *ptr = &structure_variable;
Access Structure member using pointer:
There are two ways to access the member of the structure using Structure pointer:
Using ( * ) asterisk or indirection operator and dot ( . ) operator.
Using arrow ( -> ) operator or membership operator.
Example;
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
6. Structure as Function :
Ans:
Structure as Function Arguments :
We can pass a structure as a function argument just like we pass any other variable or
an array as a function argument.
Example:
#include<stdio.h>
struct Student
{
char name[10];
int roll;
};
void main()
{
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
7. Self-referential structure
Ans:
a structure that is pointing to the structure of the same type is known as a
self-referential structure.
Self-referential structures are mainly used for the implementation of dynamic
data structures like tree, linked list, etc.
8. Unions :
Ans:
Unions :
Unions are conceptually similar to structures. The syntax to declare/define a union is also
similar to that of a structure. The only difference is in terms of storage. In structure each
member has its own storage location, whereas all members of union use a single shared
memory location which is equal to the size of its largest data member.
This implies that although a union may contain many members of different types, it cannot
handle all the members at the same time. A union is declared using the union keyword.
Syntax:
union item
{
int m;
float x;
char c;
}It1;
This declares a variable It1 of type union item. This union contains three members each with
a different data type. However only one of them can be used at a time. This is due to the fact
that only one location is allocated for all the union variables, irrespective of their size. The
compiler allocates the storage that is large enough to hold the largest variable type in the
union.
In the union declared above the member x requires 4 bytes which is largest amongst the
members for a 16-bit machine. Other members of union will share the same memory
address.
union test
{
int a;
float b;
char c;
}t;
#include <stdio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch = 'z';
printf("%d\n", it.a);
printf("%f\n", it.b);
printf("%c\n", it.ch);
return 0;
}
Output:
-26426
20.1999
Z
As you can see here, the values of a and b get corrupted and only variable c prints the
expected result. This is because in union, the memory is shared among different data types.
Hence, the only member whose value is currently stored will have the memory.
In the above example, value of the variable c was stored at last, hence the value of other
variables is lost.
9. Enumerated data type
Ans:’
Enumeration is a user defined datatype in C language. It is used to assign names to the
integral constants which makes a program easy to read and maintain. The keyword “enum” is
used to declare an enumeration.
The enum keyword is also used to define the variables of enum type. There are two ways to
define the variables of enum type as follows.
Example
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed,
Thur, Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues,
Wedn, Thurs, Frid, Satu, Sund);
return 0;
}
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12
In the above program, two enums are declared as week and day outside the main() function.
In the main() function, the values of enum elements are printed.
File is a collection of bytes that is stored on secondary storage devices like disk. There are
two kinds of files in a system. They are,
There are 4 basic operations that can be performed on any files in C programming language.
They are,
Opening/Creating a file
Closing a file
Reading a file
Writing in a file
Let us see the syntax for each of the above operations in a table:
r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten.
a – Opens a file in append mode. It returns null if file couldn’t be opened.
r+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
w+ – opens a file for read and write mode and sets pointer to the first character in
the file.
a+ – Opens a file for read and write mode and sets pointer to the first character in
the file. But, it can’t modify existing contents.
EXAMPLE PROGRAM FOR FILE OPEN, FILE WRITE AND FILE CLOSE
/ * Open, write and close a file : */
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” \
“ to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
File Input/Output
A file represents a sequence of bytes on the disk where a group of related data is stored. File
is created for permanent storage of data. It is a ready made structure.
Function description
mode description
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.
Input/Output operation on File
In the above table we have discussed about various file I/O functions to perform
reading and writing on file. getc() and putc() are the simplest functions which can be used to
read and write individual characters to a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same
file but in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which
can then be printed on the console using standard printf() function.
11.