Sei sulla pagina 1di 14

Programming in C

Structures & Union


Ordinary variables can hold one piece of information and array can hold number of pieces of
information of same data type. But sometimes it is necessary to store information of different data types
as a single unit.
Ex: Student details contains Student no, student name, student average
Employee details contains Employee no, employee name, employee salary
Book details contains Book name, book price, book author, book code

Ordinary variable manipulation:


no
int no=101; 101 raj 101

char name[20]=”raj”; name avg


float avg=99.99
Array manipulation:
int no[10];
char name[10][20];
float avg[10];
Structure definition:
Structure is a user defined data type. A Structure is a collection of heterogeneous collection of data
elements under a single name.
Structure manipulation:
struct std
101 102
{
raj riya
int no;
char name[20];
99 98
float avg;
}s1,s2; s1 s2

Syntax for creating a structure:


To create a structure we should use the keyword as “struct”.
struct <tagname>
{
Datatype member 1;
Datatype member 2;
--------------------;
--------------------;
};

1
Programming in C

The keyword struct is used to declare a structure.


ex:-
struct student
{
int sno;
char name[20];
float avg;
};
Note: A new data type is created – struct student
Declaring a structure variable: .
A structure variable declaration must hold the following elements
1.”struct “keyword.
2.structure tagname
3.variable names separated by commas
4.semicolon at the end
Declaration of structure variables can be done in following ways
1.At the time of creating the structure.
struct tagname
{
Datatype member1;
Datatype member2;
------------------------
------------------------
}variable1,variable2,…………variable n;
Or
2.After creating the structure
struct tagname
{
Datatype member1;
Datatype member2;
------------------------
------------------------
};
struct student variable1,variable2,………..variable n;
Example:
At the time of creating the structure:
struct student
{

2
Programming in C
int no;
char name[20];
float avg;
}s1,s2;
s1 and s2 are two structure variables of struct student type.
Initializating the structure variables:
struct student
{
int no;
char name[20];
float avg;
};
struct student s1={101,”raj”,99.99};
struct student s2={102,”riya”,”98.50};
Accessing of the structure members
structure members can be accessed by linking the members with the structure variables using the member
operator”.”.member operator is also referred as “dot operator” or “period operator”.
Write a program to accept student number,name,avg.
# include <stdio.h>
struct std
{
int no;
char name[20];
float avg;
}s1;
void main()
{
clrscr();
printf("Enter student no:");
scanf("%d",&s1.no);
printf("Enter student name:");
scanf("%s",&s1.name);
printf("Enter average..:");
scanf("%f",&s1.avg);
printf("\n\n%d %s %f",s1.no,s1.name,s1.avg);
getch();
}
Note: only one student information can be accepted.
Array of structures:
Several structure variables grouped into one array is referred to as an array of structures.
Example :
#include <stdio.h>
struct std
{
int no;
char name[20];

3
Programming in C
float avg;
}s[100];
void main()
{
int i,n;
clrscr();
printf("How many students..:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter student no:");
scanf("%d",&s[i].no);
printf("Enter student name:");
scanf("%s",&s[i].name);
printf("Enter average..:");
scanf("%f",&s[i].avg);

}
printf("\n\nStudent details...");
for(i=0;i<n;i++)
printf("\n%d %s %f",s[i].no,s[i].name,s[i].avg);
getch();
}
Structure assignment(copying one structure to another structure)
In c,value of one structure variable can be assigned to other variable of same structure.
# include <stdio.h>
struct student
{
int no;
char name[20];
float avg;
}s1;
void main()
{
struct student s1={65,”Aditya”,85.45};
struct student s2;
s2=s1;
clrscr();
printf("\n\n%d %s %f",s2.no,s2.name,s2.avg);
getch();
}
How to find the size of a structure
Size of structure can be evaluated by using “sizeof” operator. It will return number of bytes to store the
members of structure. it has the following syntax.
sizeof(structure variable);
Example
# include <stdio.h>
struct student
{
int no;

4
Programming in C
char name[20];
float avg;
}s1;
void main()
{

clrscr();
printf("%d”sizeof(s1));
getch();
}
Nested structure
A structure within another structure is called a nested structure.
A structure that contains another structure as its member is called nested structure.
Example
#include<stdio.h>
struct department
{
char name[25];
struct staff
{
char name[25];
char designation[25];
}s={“lalli”,”lecturer”};
}d={“dcme”};
void main()
{
clrscr();
printf(“department name%d”,d.name);
printf(“name of the staff member %s”,d,s.name);
printf(“designation of the staff %s”,d.s.designation);
getch();
}
Use of pointer to structure
In c language pointers can also be applied to structures.it is possible to have pointers pointing to a
structure in the same way as pointers pointing to int,float,and char.such pointers are known as structure
pointers. the structure pointer uses -> indirection operator in order to access structure elements.
Example:
# include <stdio.h>
struct student
{
int no;
char name[20];
float avg;
}s1={65,”lalli”,89};
void main()
{
int *ptr;
clrscr();
ptr=&s1;

5
Programming in C
printf(“name is %s”,ptr->name);
printf(“no is %d”,ptr->no);
printf(“average is %f”ptr->avg);
getch();
}

Structure as function arguments


A copy of entire structure is passed to a function ,but any modifications made to it will not be reflected in
the calling function .the called function must return the structure to the calling function to reflect the
changes.
Example: A copy of complete structure can be passed as a argument using call by value method
# include <stdio.h>
struct std
{
int no;
char name[20];
float avg;
}s;
void disp(struct std s);
void main()
{
int i;
float test;
clrscr();
printf("Enter student no:");
scanf("%d",&s[i].no);
printf("Enter student name:");
scanf("%s",&s[i].name);
printf("Enter average..:");
scanf("%f",&test);
s.avg=test;
disp(s);
getch();
}
void disp(struct std s)
{
printf("\n%d %s %f",s.no,s.name,s.avg);
}
Example: Address of the complete structure can be passed as a argument using call by reference
method
# include <stdio.h>
struct std
{
int no;
char name[20];
}s[100];
void disp(struct std *);
int n,i;

6
Programming in C
void main()
{
float test;
clrscr();
printf("How many students..:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter student no:");
scanf("%d",&s[i].no);
printf("Enter student name:");
scanf("%s",&s[i].name);
}
disp(&s);
getch();
}
void disp(struct std *x)
{
for(i=0;i<tar;i++)
{
printf("\n At %u location is %d %s ",x,x->no,x->name);
x++; /* moves to next record */
}
}

Self referential structures


A structure definition which includes at least one member as a pointer to the same structure is known as
self referential structures.
Example:
struct student
{
char name[50];
int rollno;
struct student *ptr;
};

Program:
#include<stdio.h>
struct student
{
int rollno;
struct student *ptr;
};
void main()
{
struct student *s1,*s2;
s1=(struct student *)malloc(sizeof(struct student));
s2=(struct student *)malloc(sizeof(struct student));
s1->rollno=101;
s1->ptr=s2;
s2->rollno=102;

7
Programming in C
s2->ptr=NULL;
while(s1!=NULL)
{
printf(“%d->”,s1->rollno);
s1=s1->ptr;
}
getch();
}

Define union
A union is a collection of data items of different datatypes.it is similar to that of a structure.but it
allocates memory for largest item is commonly for all members.
Use of union
By the Use of union we can save the memory space efficiently. because it allocates memory for largest
item is commonly for all members .
Difference between structures and union
Structure union
1.syntax of declaration 1.syntax of declaration

struct tagname union tagname


{ {
Datatype member1; datatype member1;
Datatype member2; datatype member2;
}; };
2.every structure member is allocated memory 2. the memory equivalent to the largest item When the
structure variable is defined. is allocated commonly for all members.
3.all the members can be assigned values at a time 3.only one member can be assigned value
at a time.
4.the usage of structure is efficient when all 4.the usage of union is efficient when the
members are actively used in the program members of it are not required to be
accessed at the same time
5.Example: 5.Example
struct student union student
{ {
char c; char c;
int x; int x;
float y; float y;
}s; }u;

8
Programming in C
Memory allocated for is 1+2+4=7bytes the memory is allocated to 4 bytes(float
is largest item)
typedef keyword:
typedef is a keyword which is used to define an alias for datatype( usually structure type of datatype).
# include <stdio.h>
typedef struct employee
{
int empno;
char ename[20];
float sal;
};

void main()
{
employee emp;
printf(“Enter employee no:”);
scanf(“%d”,&emp.empno);
printf(“Enter employee name:”);
fflush(stdin);
gets(emp.ename);
printf(“Enter employee salary:”);
scanf(“%f”,&emp.sal);
disp(emp);
getch();
}
void disp(employee x)
{
printf(“\n %d - %s - %f”,x.empno,x.ename,x.sal);
}
C program for read, write and addition and subtraction of two complex numbers.
#include <stdio.h>
#include <stdlib.h>

struct complex
{
int real, img;
};

void main()
{
int choice, temp1, temp2, temp3;
struct complex a, b, c;
printf("Enter a and b where a + ib is the first complex number.");
printf("\na = ");
scanf("%d", &a.real);
printf("b = ");
scanf("%d", &a.img);
printf("Enter c and d where c + id is the second complex number.");
printf("\nc = ");
scanf("%d", &b.real);
printf("d = ");
scanf("%d", &b.img);
c.real = a.real + b.real;
c.img = a.img + b.img;

9
Programming in C
if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di",c.real,c.img);
else
printf("Sum of two complex numbers = %d %di",c.real,c.img);
c.real = a.real - b.real;
c.img = a.img - b.img;
if ( c.img >= 0 )
printf("Difference of two complex numbers = %d + %di",c.real,c.img);
else
printf("Difference of two complex numbers = %d %di",c.real,c.img);

Basics of File management system and preprocessor directives


Define file: A file is a collection of records,where each record provides an information to the
User the files are stored permanently on the secondary storage device(disk) and can be access through a

set of library functions.


Syntax:FILE pointertype;

Example:FILE *fp;
Here fp is a pointer to the file structure.this acts as a link between the operating system and a program.
Concept of file opening in various modes
1.”r”(read)mode.
2.”w”(write)mode.
3.”a”(append)mode.
4.”r+”(read and write mode.
5.”w+”(write and read mode.
6.”a+”(append and read mode.
7.”wb”(write binary) mode.
8.”rb”(read binary)mode.
9.”ab”(append binary)mode.
1.”r”(read)mode:This mode opens the file that already exists for reading only.if the file to be read does
not exist then an error occurs.
Syntax:fp=fopen(“read.txt”,”r”);
2.”w”(write)mode:The previous contents of the existing file are discarded without any confiramation.
Syntax:fp=fopen(“read.txt”,”w”);

10
Programming in C
3.”a”(append)mode:This mode is used to append or add data to an existing file.the file pointer points to
the end of the existing file.so that data can be appended .
If a file does not exist then a file with a specified name is opened for writing
Syntax:fp=fopen(“read.txt”,”a”);
4. ”r+”(read and write mode:This mode is used for both reading and writing the data in the file.if a file
does not exist then a file NULL is returned to the file pointer.
Syntax:fp=fopen(“read.txt”,”r+”);
5.”w+”(write and read mode: This mode is used for reading and writing the data on the file.if the file
already exists then the contents of that file are eliminated.if the file does not exist then a new file is
created.
Syntax:fp=fopen(“read.txt”,”w+”);
6.”a+”(append and read mode:
This mode is used to read as well as data can be added by the usage of “a+” mode.
Syntax:fp=fopen(“read.txt”,”a+”);
7.”wb”(write binary) mode:
This mode is used to open the binary file in write mode.
Syntax:fp=fopen(“read.txt”,”wb”);
8.”rb”(read binary)mode:
This mode is used to read the binary file.
Syntax:fp=fopen(“read.txt”,”rb”);
9.”ab”(append binary)mode:
This mode is used to add the data at the end of a binary file.
Syntax:fp=fopen(“read.txt”,”rb”);
Concept of closing of a file:
To close a file we should use the function as fclose();
Syntax: fclose(file pointer);
Ex:fclose(fp);
Concept of input/output operations on a file
1.fprintf() function:
This function is used for writing records into a file.its function is analogous to the printf() function.the
function outputs the matter given in quotations in fprintf() to the display screen.this function handles a
group of mixed data simultaneously.
Syntax:fprintf(file_descriptor,”format string”,list);
Example:fprintf(fp,”%d%s%f”,age,name,marks);
2.fscanf():This function is used for reading records from the file.fscanf() function is analogous to the
scanf() function except that it works on files.

11
Programming in C
syntax:
Fscanf(fp,”formatstring”,address of list);
Example:fscanf(fp,”%d%s%f”,&age,&name,&price);
3.getc()function:This function is used to read characters from the file that has been opened for read
operation.
Syntax:getc(file_pointer);
4.putc()
This function writes a character to a file that has been opened in write mode.this function can also handle
only one character.
Syntax:putc(character_variable,file_pointer).
Example:putc(a,fp);
5.Putw()
This function writes an integer to a file.
Syntax:putw(variable,file_pointer);
Example:putw(i,fp);
The integer value i written to the file pointed by ‘fp’.
6.getw()
This function reads an integer from a file.
Syntax:getw(file_pointer);
Example:getw(fp);
Concept of random access to files
In sequential access of file, data is read from or written to the sequentially i.e. from beginning of
the file to end of file in the order. it is achieved using functions fprintf(),fscanf(),getc(),putc() etc.In
random access of file, a particular part of a file can be accessed irrespective of other parts.
random access of file is achieved with the help of functions fseek(),ftell,and rewind() available in
i/o library.
a)ftell():This function gives the current position of file pointer in terms of bytes from the beginning.
syntax:n=ftell(fp);
here ‘n’ gives the current position of the file pointer from beginning.
b)rewind()
this function takes file pointer to the starting of the file and resets its.
syntax:rewind(fp);
3.fseek()
it is a file function that is used to move the file pointer to the desired location in the file.it is generally
used when a particular patr of the file is to be accessed.the main purpose of file fseek() is to position the
file pointer to any locations on the stream.

12
Programming in C
syntax:fseek(filepointer,offset,position);
a.file pointer.
It is a file pointer.
b.offset
it specifies the number or variable of type long to reposition the file pointer.it tells ths number of bytes to
be moved.offset can either be positive or negative number,where positive integer is used to reposition the
pointer forward to anylocations on the stream.
c.position
it specifies the current position .
value position
0 beginning of file
1 current position
2 End of file(EOF)
the fseek() returns zero,if all the operations are performed sucessfully or -1 ifan error occurs such as eof is
reached
File management in C:
Till now we have been doing console I/O i.e reading data from the input device (Keyboard) and sending
output to output device (screen).
Reading : keyboard Program
Writing : Program Screen
Use of Disk I/O:
Disk I/O means storing the data on a secondary storage device using files.
Disk I/O is used for developing database applications.
File is a collection of bytes stored on a secondary storage device.
Reading: Disk Program Screen/Disk
Writing: Keyboard/Disk Program Disk
File operations:
Creating a new file and inserting data.
Opening the existing file for append/update/delete.
There are 2 types of files
Text files
Text files stores character data
Text files are readable
Text files are processed sequentially (character by character)
Binary files
Binary files stores data in binary format

13
Programming in C
Binary files are non readable
File functions:
Syntax for declaring file pointer:
FILE <Pointer variable>
Ex:-
FILE *fp;
Syntax for opening file:
fp=fopen(“file name”,”mode”)
If the file is available fopen() returns reference of the file and assigns to fp variable, other wise it returns
NULL.
File opening modes are:
r – Read mode
w – Write mode
a – Append mode
t – indicates text file
b – indicates binary file
+ - dual mode.

14

Potrebbero piacerti anche