[go: up one dir, main page]

0% found this document useful (0 votes)
11 views21 pages

unit-5

The document provides an overview of structures in C programming, detailing how to create, declare, and access structure members, including nested structures and arrays of structures. It also covers structure pointers, passing structures to functions, self-referential structures, unions, enumerated data types, and basic file operations in C. The document includes syntax examples and code snippets to illustrate each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views21 pages

unit-5

The document provides an overview of structures in C programming, detailing how to create, declare, and access structure members, including nested structures and arrays of structures. It also covers structure pointers, passing structures to functions, self-referential structures, unions, enumerated data types, and basic file operations in C. The document includes syntax examples and code snippets to illustrate each concept.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit-V

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

To create a structure in C, the struct keyword is used followed by the tag


name of the structure. Then the body of the structure is defined, in which the
required data members (primitive or user-defined data types) are added.

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.

Accessing members of the structure or Initialize Structure:

There are two ways to access structure members:


1. By . (member or dot operator)
2. By -> (structure pointer operator)

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;

//store second employee information


e2.id=102;
strcpy(e2.name, "James Bond");
e2.salary=126000;

//printing first employee information


printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);

//printing second employee information


printf( "employee 2 id : %d\n", e2.id);
printf( "employee 2 name : %s\n", e2.name);
printf( "employee 2 salary : %f\n", e2.salary);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

2. Nested Structure (or) Embedded Structure


Ans:
C provides us the feature of nesting one structure within another structure
The structure can be nested in the following ways.
 By separate structure
 By Embedded structure
Separate structure:
Here, we create two structures, but the dependent structure should be used inside the main
structure as a member. Consider the following example.

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;

//printing first employee information


printf( "parant name : %s\n", parant1.name);
printf( "student name : %s\n", parant1.stu1.name);
printf( "student id : %d\n",parant1.stu1.id );
return 0;
}

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.

 The most common use of structure in C programming is an array of structures.


 To declare an array of structure, first the structure must be defined and then an
array variable of that type should be defined.
 For Example − struct book b[10]; //10 elements in an array of structures of type
‘book’
Let's see an example of an array of structures that stores information of 5 students
and prints it.

#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

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, 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.

struct structure_name *ptr;


struct name {
member1;
member2;
.
.
}variablename;

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("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

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 show(struct Student st);

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);
}

void show(struct Student st)


{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}

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.

Accessing a Union Member


Syntax for accessing any union member is similar to accessing structure members,

union test
{
int a;
float b;
char c;
}t;

t.a; //to access members of union t


t.b;
t.c;

Time for an Example

#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.

Here is the syntax of enum,


enum enum_name{const1, const2, ....... };

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.

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};


enum week day;

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.

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);
}

10. WHAT IS FILE?


Ans:

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,

 Text files (ASCII)


 Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of
text files.

BASIC FILE OPERATIONS IN C PROGRAMMING:

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

printf("Closing the file test.c") ;


fclose(fp) ;
return 0;
}
OUTPUT:
Opening the file test.c in write mode
Enter some text from keyboard to write in the file test.c
Hai, How are you?
Closing the file test.c

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.

In C language, we use a structure pointer of file type to declare a file.


FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are
the functions.

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file


getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created)
file.
filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,

mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode


rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

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);

// closing the file pointer


fclose(fp);
return 0;
}

Reading and Writing to File using fprintf() and fscanf()


#include<stdio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);

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.

You might also like