Professional Documents
Culture Documents
Unit III Structure & Union
Unit III Structure & Union
Data Types
C programming language which has the ability to divide the data into different types.
The type of a variable determine the what kind of values it may take on. The various
data types are.
• Array, Strings
A structure is a user defined data type that groups logically related data items of
different data types into a single unit. All the elements of a structure are stored at
contiguous memory locations. A variable of structure type can store multiple data items of
different data types under the one name. As the data of employee in company that is name,
Employee ID, salary, address, phone number is stored in structure data type.
Defining of Structure
A structure has to defined, before it can used. The syntax of defining a structure is
struct <struct_name>
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};
Example of Structure
struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
Memory Space Allocation
A structure has to declared, after the body of structure has defined. The syntax of
declaring a structure is
Struct <struct_name>
<variable_name>;
The members of individual structure variable is initialize one by one or in a single statement.
2) e1.emp_id=1;
e1.dept_no=1;
e1.name=“Hemant”;
e1.age=35;
e1.salary=12000;
The structure members cannot be directly accessed in the expression. They are accessed by
using the name of structure variable followed by a dot and then the name of member variable.
The method used to access the structure variables are e1.emp_id, e1.name, e1.salary,
e1.address, e1.dept_no, e1.age. The data with in the structure is stored and printed by this
Structure Assignment
The value of one structure variable is assigned to another variable of same type using
assignment statement. If the e1 and e2 are structure variables of type employee then the
statement
e1 = e2;
assign value of structure variable e2 to e1. The value of each member of e2 is assigned to
corresponding members of e1.
#include<stdio.h>
#include<conio.h>
struct employee
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
void main ( )
scanf(“%d”,&e1.emp_id);
scanf(“%s”,e1.name);
scanf(“%f”,&e1.salary);
scanf(“%d”,&e1.dept_no);
scanf(“%d”,&e1.age);
scanf(“%d”,&e2.emp_id);
scanf(“%s”,e2.name);
scanf(“%f”,&e2.salary);
scanf(“%s”,e2.address);
scanf(“%d”,&e2.dept_no);
scanf(“%d”,&e2.age);
e2.emp_id);
e2.name);
e2.salary);
e2.address);
e2.dept_no);
getch();
Output of Program
Array of Structure
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
char address[50];
int dept_no;
int age;
};
void main ( )
{
struct employee e1[5];
int i;
for (i=1; i<=100; i++)
{
printf (“Enter the employee id of employee”);
scanf (“%d”,&e[i].emp_id);
printf (“Enter the name of employee”);
scanf (“%s”,e[i].name);
printf (“Enter the salary of employee”);
scanf (“%f”,&e[i].salary);
<variable_name>;
……..}<struct_variable>;
<data_type> <variable_name>; }
Example of Structure within Structure
struct employee
{
int emp_id;
char name[20];
float salary;
int dept_no;
struct date
{ int day;
int month;
int year;
}doj;
};
C language can define a pointer variable of structure type. The pointer variable to
structure variable is declared by using same syntax to define a pointer variable of
data type. The syntax to define the pointer to structure
struct <struct_name> *<pointer_var_name>;
For Example:
struct employee *emp;
It declare a pointer variable “emp” of employee type.
The member of structure variable is accessed by using the pointer variable with
arrow operator(->) instead of period operator(.). The syntax to access the
pointer to structure.
pointer_var_name->structure_member;
For Example:
Emp->name;
Here “name” structure member is accessed through pointer variable emp.
void main ( )
{
struct employee e1;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e1.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e1.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e1.salary);
printdata (struct employee e1);
getch();
}
void printdata( struct employee emp)
{
printf (“\nThe employee id of employee is : %d”, emp.emp_id);
printf (“\nThe name of employee is : %s”, emp.name);
printf (“\nThe salary of employee is : %f”, emp.salary);
}
The function can return a variable of structure type like a integer and float variable. The
program to return a structure from function.
#include <stdio.h>
#include <conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};
void main ( )
{
struct employee emp;
emp=getdata();
printf (“\nThe employee id of employee is : %d”, emp.emp_id);
printf (“\nThe name of employee is : %s”, emp.name);
printf (“\nThe salary of employee is : %f”, emp.salary);
getch();
}
union groups logically related variables into a single unit. The union data type allocate
the space equal to space need to hold the largest data member of union. The union allows
different types of variable to share same space in memory. There is no other difference
between structure and union than internal difference. The method to declare, use and
access the union is same as structure.
Defining of Union
union <union_name>
{
<data_type> <variable_name>;
<data_type> <variable_name>;
……..
<data_type> <variable_name>;
};
Example of Union
1) The memory occupied by structure variable is the sum of sizes of all the members
but memory occupied by union variable is equal to space hold by the largest data member
of a union.
2) In the structure all the members are accessed at any point of time but in union only
one of union member can be accessed at any given time.
Application of Structures
Structure is used in database management to maintain data about books in library,
items in store, employees in an organization, financial accounting transaction in
company. Beside that other application are
1) Changing the size of cursor.
2) Clearing the contents of screen.
3) Drawing any graphics shape on screen.
4) Receiving the key from the keyboard.
5) Placing cursor at defined position on screen.
6) Checking the memory size of the computer.
7) Finding out the list of equipments attach to computer.
8) Hiding a file from the directory.
9) Sending the output to printer.
10) Interacting with the mouse.
11) Formatting a floppy.
12) Displaying the directory of a disk.
Storage Class in C
Introduction
Storage class explain the behavior of the variable in terms of scope and lifetime, it also
determine the initial of the variable.
Scope of the variable is the region over which the variable is visible or valid.
Life time of the variable is the time during which memory is associated with the variable.
Initial value is the value assigned to the variable implicitly if no value is assigned to it by the
programmer.
There are four types of storage class available in C:
Auto
Extern
Static
Register
AUTO
All local variables has this storage class. Default value is the
garbage value.
Scope of the variable is only between the blocks where it is declared.
Lifetime is till the control remains within the block or function where these variables are
defined.
These variables are destroyed whenever block ends or function jump occur.
To declare auto storage class auto keyword is used.
Example:
auto int n;
Auto keyword is optional all the local variables by default fall under this storage class.
Example:
int n;
Extern
Scope is through out the program. Lifetime is till the end of the
program. Initial value is 0.
Extern keyword is used to declare the variable of this storage class.
extern int x;
By default global variable has this storage class.
STATIC
C Pre-processor
Six phases to execute C:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
C Preprocessor
All preprocessor directives begin with #
Possible actions
Inclusion of other files
Definition of symbolic constants & macros
Conditional compilation of program code
Conditional compilation of preprocessor directives
Preprocessor Directives
#define for symbolic constants
#define identifier text
Creates symbolic constants
The “identifier” is replaced by “text” in the program
Example
#define PI 3.14
area = PI * radius * radius;
#if !defined(NULL)
#define NULL 0
#endif
#if 0
code prevented from compiling
#endif
FILE HANDLING
What is a File?
● A file is a collection of related data that a
computers treats as a single unit.
● Computers store files to secondary storage so
that the contents of files remain intact when a
computer shuts down.
● When a computer reads a file, it copies the file
from the storage device to memory; when it
writes to a file, it transfers data from memory to
the storage device.
● C uses a structure called FILE (defined in
stdio.h) to store the attributes of a file.
Steps in Processing a File
1. Create the stream via a pointe2. Open the file, associating the stream name with the file
name. Create the stream via a pointer variable using the FILE structure:
FILE *p;
2. Open the file, associating the stream name with the file
name.
3. Read or write the data.
4. Close the file.
The basic file operations are
● fopen - open a file- specify how its opened
(read/write) and type (binary/text)
● fclose - close an opened file
● fread - read from a file
● fwrite - write to a file
● fseek/fsetpos - move a file pointer to
somewhere in a file.
● ftell/fgetpos - tell you where the file pointer is
located.
File Open Modes
More on File Open Modes
Additionally,
● r+ - open for reading and writing, start at beginning
● w+ - open for reading and writing (overwrite file)
● a+ - open for reading and writing (append if file exists)
File Open
● The file open function (fopen) serves two purposes:
– It makes the connection between the physical file and the stream.
– It creates “a program file structure to store the information” C needs to process the file.
● Syntax:
filepointer=fopen(“filename”, “mode”);
More On fopen
● The file mode tells C how the program will use the file.
● The filename indicates the system name and location for the file.
● We assign the return value of fopen to our pointer variable:
spData = fopen(“MYFILE.TXT”, “w”);
spData = fopen(“A:\\MYFILE.TXT”, “w”);
More On fopen
Closing a File
● When we finish with a mode, we need to close the file before ending the program or
beginning another mode with that same file.
● To close a file, we use fclose and the pointer variable:
fclose(spData);
fprintf()
Syntax:
fprintf (fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(“out.txt”,”w”);
fprintf (fp, "%d %f %c", i, x, ch);
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",&i);
fgetc()
Syntax:
identifier = fgetc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = fgetc (fp);
fputc()
End of File
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f \n ", a, b, c) ;
printf (“ %f %d %f \n ", e, f, g) ;
}
Example
#include <stdio.h>
#include<conio.h>
int main()
{
char ch;
FILE *fp;
fp=fopen("out.txt","r");
while(!feof(fp))
{
ch=getc(fp);
printf("\n%c",ch);
}
fcloseall( );
}
fread ()
Declaration:
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);
Remarks:
fread reads a specified number of equal-sized
data items from an input stream into a block.
ptr = Points to a block into which data is read
size = Length of each item read, in bytes
n = Number of items read
stream = file pointer
Example:
#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("fred.txt", “r”))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}
fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n, FILE*stream);
Remarks:
fwrite appends a specified number of equal-sized data items to an
output file.
ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
Example:
#include <stdio.h>
int main()
{
char a[10]={'1','2','3','4','5','6','7','8','9','a'};
FILE *fs;
fs=fopen("Project.txt","w");
fwrite(a,1,10,fs);
fclose(fs);
return 0;
}
fseek()
This function sets the file position indicator for the stream pointed to by stream
or you can say it seeks a specified place within a file and modify it.
Seeks from beginning
SEEK_SET
of file
Seeks from current
SEEK_CUR
position
SEEK_END Seeks from end of file
Example:
#include <stdio.h>
int main()
{
FILE * f;
f = fopen("myfile.txt", "w");
fputs("Hello World", f);
fseek(f, 6, SEEK_SET); SEEK_CUR, SEEK_END
fputs(" India", f);
fclose(f);
return 0;
}
ftell()
Example
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("MYFILE.TXT", "w");
fprintf(stream, "This is a test");
printf("The file pointer is at byte %ld\n", ftell(stream));
fclose(stream);
return 0;
}
Questions
Part-A
2. Define Structure in C.
Structure can be defined as a collection of different data types which are grouped
together and each element in a C structure is called member. To access structure
members in C, structure variable should be declared. The keyword used is struct.
struct tag
{
datatype member 1;
datatype member 2;
………
………
datatype member n;
};
where struct is a keyword, tag is a name that identifies structures, member 1,
member 2,….. member n are individual member declarations.
statements
a. The keyword struct
b. The structure name
c. List of variable names separated by commas
d. Terminating semicolon
struct library_books
{
char title[20]; char author[15]; int pages;
float price;
};
struct library_books b1,b2,b3;
union tag
{
member definition;
member definition;
....
Member definition;
16. How will you access the structures member through pointers?
The structures member can be accessed through pointers by the following ways
a. Referencing pointer to another address to access memory
b. Using dynamic memory allocation
19. What are the pre-processor directives? (Jan 2014, May 2014, 2015)
Preprocessor directives are the commands used in preprocessor and they begin with
“#” symbol. Before a C program is compiled in a compiler, source code is processed
by a program called preprocessor. This process is called preprocessing.
Syntax: #define
Macro
This macro defines constant value and can be any of the basic data types.
Syntax: #include <file_name>
Header file
The source code of the file “file_name” is included in the main program at
inclusion
the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program before
compilation
compilation with respect to the condition.
Syntax: #undef, #pragma
Unconditional
#undef is used to undefine a defined macro variable. #Pragma is used to call
compilation
a function before and after main function in a C program.
25. Define Macro in C. What is the use of #define preprocessor? (Nov 2014)
A macro can be defined as the facility provided by the C preprocessor by which a
token can be replaced by the user defined sequence of characters. Macros are defined
with the help of define directive. Its format is: #define identifier replacement.
#define TABLE_SIZE 100
a. File name
b. File Position
c. File Structure
d. File Access Methods
e. Attributes flag
33. What is the use of functions fseek(), fread(), fwrite() and ftell()?
a. fseek(f,1,i)Move the pointer for file f of a distance 1 byte from location i.
b. fread(s,i1,i2,f)Enter i2 dataitems, each of size i1 bytes from file f to string s.
c. fwrite(s,i1,i2,f)send i2 data items,each of size i1 bytes from string s to file f.
d. ftell(f)Return the current pointer position within file f.
e. The data type returned for functions fread,fseek and fwrite is int and ftell is
long int.
35. What are the statements used for reading a file? (Nov 2014)
a. FILE*p;Initialize file pointer.
b. fp=fopen(“File_name” ”r”);Open text file for reading.
c. Getc(file_pointer_name);Reads character from file.
d. fgets(str,length,fp); Reads the string from the file.
36. What is the difference between getc() and getchar()? (May 2015)
int getc(FILE * stream) gets the next character on the given input stream „s file
pointer to point to the next character.
int getchar(void) returns the next character on the input stream stdin.
37. Differentiate text file and binary file.
Text file Binary File
a. Data are human readable characters a. Data is in the form of sequence of bytes.
b. Each line ends with a newline character. b. There are no lines or newline character.
c. Ctrl+z or Ctrl+d are end of file character c. An EOF marker is used.
d. Data is read in forward direction only d. Data may be read in any direction.
e. Data is converted into the internal format e. Data stored in file are in same format
before being stored in memory that they are stored in memory
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 appended mode.
r+ Opens a text file in both reading and writing mode.
w+ Opens a text file in both reading and writing mode.
Part - B