c concepts
c concepts
4.2 UNION
Unions are quite similar to the structures in C. Union is also a derived type as structure.
Union can be defined in same manner as structures just the keyword used in defining union in
union where keyword used in defining structure was struct.
union car{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
union car{
union car{
char name[50];
char name[50];
OR int price;
int price;
};
}c1, c2, *c3;
-------Inside Function-----------
union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union car is
created.
Accessing members of an union
The member of unions can be accessed in similar manner as that structure. Suppose, we
you want to access price for union variable c1 in above example, it can be accessed as c1.price.
If you want to access price for union pointer variable c3, it can be accessed as (*c3).price or as
c3->price.
Union:
Union is another compound data type like structure. Union is used to minimize memory
utilization. In structure each member has the separate storage location. but in union all the
members share the common place of memory. so a union can handle only one member at a time.
Declaration of Union:
The general format for declaring union is,
union tagname
{
datatype member1;
datatype member2;
..
...
datatype member N;
};
Where union is the keyword. Tag name is any user defined data types.
Example:
union personal
{
char name[25];
int age;
float height;
};
In the above example ‘union bio’ has 3 members first member is a character array ‘name’
having to 10 character (10 bytes)second member is an integer ‘ age’ that requires 2 bytes third
member is a float as four bytes, all the three members are different data types.
Here all these 3 members are allocated with common memory . That means, the compiler
allocates a piece of storage that is large enough to hold the all type in the union.
In case of structure it will be occupies a separate memory of each data types.
Advantages:
1. It is used to minimize memory utilization.
2. it is used to convert data from one type to another type.
Example:
union test
{
int sum;
float average;
};
EX. 4.1 PROGRAMS USING STRUCTURES AND UNIONS
C Program to Store Information of Single Variable
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks);
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}
EX 4.2 Source Code to Store Information of 10 students Using Structure
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s[10];
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}
Output
Enter information of students:
For roll number 1
Enter name: Tom
Enter marks: 98
For roll number 2
Enter name: Jerry
Enter marks: 89
.
Displaying information of students:
Information for roll number 1:
Name: Tom
Marks: 98
Source Code Demonstrate the Dynamic Memory Allocation for Structure
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
char c[30];
};
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
/* allocates the memory for n structures with pointer ptr pointing to the base address. */
ptr=(struct name*)malloc(n*sizeof(struct name));
for(i=0;i<n;++i){
printf("Enter string and integer respectively:\n");
scanf("%s%d",&(ptr+i)->c, &(ptr+i)->a);
}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t\n",(ptr+i)->c,(ptr+i)->a);
return 0;
}
Output
Enter n: 2
Enter string and integer respectively:
Programming
22
Enter string, integer and floating number respectively:
Structure
33
Displaying Information:
Programming 22 Memory allocation in structures
Structure 33
Program to demonstrate UNION Name Salary Worker no
#include <stdio.h> 32 bytes 4 bytes 4 bytes
Union job { //defining a union
char name[32];
float salary;
int worker_no; Memory allocation in union
}u;
Struct job1 { Name
char name[32]; 32 bytes
float salary;
int worker_no;
}s;
int main(){
printf("size of union = %d",sizeof(u));
printf("\nsize of structure = %d", sizeof(s));
return 0;
}
Output
Size of union = 32
Size of structure = 40
There is difference in memory allocation between union and structure as suggested in
above example. The amount of memory required to store a structure variables is the sum of
memory size of all members. But, the memory required to store a union variable is the memory
required for largest element of an union.
4.2 Enumeration (or enum) in C
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
Variables of type enum can also be defined. They can be defined in two ways:
// In both of the below cases, "day" is
// defined as the variable of type week.
// Or
int main()
day = Wed;
printf("%d",day);
return 0;
Output:
2
In the above example, we declared “day” as the variable and the value of “Wed” is allocated to
day, which is 2. So as a result, 2 is printed.
#include<stdio.h>
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
In this example, the for loop will run from i = 0 to i = 11, as initially the value of i is Jan which is
0 and the value of Dec is 11.
4.3 typedef in C
The typedef is a keyword used in C programming to provide some meaningful names to
the already existing variable in the C program. It behaves similarly as we define the alias for the
commands. In short, we can say that this keyword is used to redefine the name of an already
existing variable.
Syntax of typedef
typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already existing variable while 'alias
name' is another name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it becomes a
tedious task if we want to declare multiple variables of this type. To overcome the problem, we
use a typedef keyword.
typedef unsigned int unit;
In the above statements, we have declared the unit variable of type unsigned int by using a
typedef keyword.
Now, we can create the variables of type unsigned int by writing the following statement:
unit a, b;
instead of writing:
unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice shortcut by providing an
alternative name for an already existing variable. This keyword is useful when we are dealing
with the long data type especially, structure declarations.
Let's understand through a simple example.
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
struct student
{
char name[20];
int age;
};
struct student s1;
In the above structure declaration, we have created the variable of student type by writing the
following statement:
struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is quite big. To
avoid such a big statement, we use the typedef keyword to create the variable of type student.
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
In the above statement, we have declared the variable stud of type struct student. Now, we can
use the stud variable in a program to create the variables of type struct student.
The above typedef can be written as:
typedef struct student
{
char name[20];
int age;
} stud;
stud s1,s2;
From the above declarations, we conclude that typedef keyword reduces the length of the code
and complexity of data types. It also helps in understanding the program.
4.4 Self Referential Structures
Self Referential structures are those structures that have one or more pointers which point to the
same type of structure, as their member.
struct node {
int data1;
char data2;
struct node* link;
};
int main()
{
struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the structure
‘node’ is a self-referential structure with ‘link’ as the referencing pointer.
An important point to consider is that the pointer should be initialized properly before
accessing, as by default it contains garbage value.
Types of Self Referential Structures
Applications:
Self referential structures are very useful in creation of other complex data structures like:
Linked Lists
Stacks
Queues
Trees
Graphs etc
4.5 FILE HANDLING AND MANIPULATION IN C
File
File is a place on disk where a group of related data is stored. Abstractly, a file is a
collection of bytes stored on a secondary storage device, which is generally a disk of some kind.
The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs
and pages from a textual document, fields and records belonging to a database, or pixels from a
graphical image.
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you want to keep
large volume of data, it is time consuming to enter the entire data. But, if file is created, these
information can be accessed using few commands. Depending upon the way file is opened for
processing, a file is classified into:
1. Text file
2. Binary file
File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file
Working with file
Creating a File:
While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program.
FILE *ptr;
Opening a File:
Opening a file is performed using library function fopen(). The syntax for opening a file in
standard I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w");
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
R Open for reading. If the file does not exist, fopen() returns NULL.
W Open for writing. If the file exists, its contents are overwritten. If
the file does not exist, it will be created.
A Open for append. i.e, Data is If the file does not exists, it will be created.
added to end of file.
r+ Open for both reading and If the file does not exist, fopen() returns NULL.
writing.
w+ Open for both reading and If the file exists, its contents are overwritten. If
writing. the file does not exist, it will be created.
a+ Open for both reading and If the file does not exists, it will be created.
appending.
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using
library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.
The Functions fprintf() and fscanf() functions.
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only
difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure
FILE
Writing to a file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
This program takes the number from user and stores in file. After you compile and run
this program, you can see a text file program.txt created in C drive of your computer. When you
open that file, you can see the integer you entered.
Similarly, fscanf() can be used to read data from file.
Reading from file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back
entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
EX: Write a C program to read name and marks of n number of students from user and store
them in a file
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Ex 2: Write a C program to read name and marks of n number of students from user and store
them in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
return 0;
}
Input/Output operation on File
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=9; counter >= 0; counter--)
{
fseek(ptr_myfile,sizeof(struct rec)*counter,SEEK_SET);
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
In this example we are using fseek to seek the last record in the file. This record we read
with fread statement and with the printf statement we print member x of the structure my_record.
As you can see the “for loop” also changed. The “for loop” will now countdown to zero. This
counter is then used in the fseek statement to set the file pointer at the desired record. The result
is that we read-in the records in the reverse order.
A last note: if you set the file position indicator to a position in a file and you want the
first position in a file then you can use the function rewind to the first position in the file. The
function rewind can be used like this:
#include<stdio.h>
struct rec /* Our structure */
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
fseek(ptr_myfile, sizeof(struct rec), SEEK_END);
rewind(ptr_myfile);
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
With the fseek statement in this example we go to the end of the file. Then we rewind to
first position in the file. Then read-in all records and print the value of member x. Without the
rewind you will get garbage