CPL Mod 5
CPL Mod 5
Drawback of arrays: arrays can be used to represent a collection of elements of the same data
type like int, float etc. They cannot be used to hold a collection of different types of elements.
Syntax of Structure Definition: structures must be first defined first for their later use. The
syntax for defining a structure is as shown below:
struct structure_name
{
datatype var1;datatype var2;
-------
};
The keyword struct declares a structure. The structure_name represents the name of the
structure. The structure definition is always terminated with a semicolon.
Example:
struct student
{
int rollno;
char name[26];int marks;
};
In the above example, student is the name of the structure. The members of the student structure
are: name, rollno and marks. A structure itself does not occupy any memory in the RAM. Memory
is allocated only when we create variables using the structure.
a) Declaring Structure Variables: A structure variable declaration is similar to the declaration
of variables of any other data types.
Syntax for Declaring Structure Variables:
struct structurename var1, var2, …., varN
Example:
{
int rollno;
char name[26];int marks;
}student;
The name student represents the structure definition associated with it and therefore can be used
to declare structure variables as shown below:
student s1, s2, s3;
b) Accessing Structure Members: We can access and assign values to the members of a
structure in a number of ways. They should be linked to the structure variables in order to
make them meaningful members.
The link between a member and a variable is established using the member operator ‘.’ whichis also
known as dot operator or period operator.
Syntax for accessing a structure member:
structure-varaible.membername
Example:
s1.name
s1.rollno
1) static initialization
2) dynamic initialization
#include<stdio.h>
struct student
{
int roll;
char name[26];
int marks;
};
void main()
{
struct student s1;
printf("Enter the students details\n");
scanf("%d %s %d", &s1.roll, s1.name, &s1.marks);
printf("The details of student:\n");
printf(“Roll no=%d\t Name=%s\t Marks=%d\n”, s1.roll, s1.name, s1.marks);
}
Program to read and print the employee information such as employee id, name &
salary using structures.
#include<stdio.h>
struct employee
{
int eid;
char name[26];
float salary;
};
void main()
{
struct employee e1;
printf("Enter the employee details\n"); scanf("%d
%s %f", &e1.eid, e1.name, &e1.salary);printf("The
details of employee:\n");
printf(“Emp id=%d\t Name=%s\t Salary=%f\n”, e1.eid, e1.name, e1.salary);
}
struct student
{
int rollno;
char name[26];int marks[6];
};
C program to enter the information like name, register number, marks in 6 subjects of
N students into an array of structures, find the average & display grade based on average
for each student.
#include<stdio.h>
struct student
{
int roll;
char name[26];int
marks[6];
};
void main()
{
struct student s[10];
int i, n, sum, j;float
avg;
printf("Enter the number of students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of student: \n");
printf("Enter the roll number\n");
scanf("%d",&s[i].roll);
printf("Enter the Name\n");
scanf(“%s”, s[i].name);
printf("Enter the Marks of each subject\n");for
(j=0;j<6;j++)
{
scanf("%d",&s[i].marks[j]);
}
}
for(i=0;i<n;i++)
{
sum=0, avg=0.0;
for(j=0;j<6;j++)
{
sum=sum+s[i].marks[j];
}
avg=(float)sum/6;
printf("Roll Number: %d, Name: %s, Avg Marks: %f \n", s[i].roll, s[i].name, avg);
if(avg>=80 && avg<=100)
{
printf("The grade is DISTINCTION\n");
}
else if(avg>=60 && avg<=79)
{
printf("The grade is FIRST CLASS\n");
}
else if(avg>=40 && avg<=59)
{
printf("The grade is SECOND CLASS\n");
}
else
{
printf("The grade is FAIL\n");
}
}
struct student
{
struct name
{
outer_structure_variable.inner_structure_variable.member_name;
Example: s1.n1.fname;
Program to read and print the student information such as reg.no, date of birth, name
& total marks using nested structures for date of birth.
#include<stdio.h>
struct dob
{
int day; int
month;int
year;
};
struct student
{
int roll;
char name[26];
struct dob d;
};
void main()
{
struct student s1;
printf("Enter the Student details:\n");
printf("Enter roll no: ");
scanf("%d",&s1.roll);
printf("Enter DOB: ");
scanf("%d %d %d",&s1.d.day,&s1.d.month,&s1.d.year);
printf("Enter name: ");
scanf("%s",s1.name);
printf("Student Details:\n");
printf("Roll:%d\t DOB:%d/%d/%d\t Name:%s" ,s1.roll, s1.d.day, s1.d.month, s1.d.year,
s1.name);
}
PASSING STRUCTURES TO FUNCTIONS: Functions are the basic building blocksof
a C program. So, it is natural for C language to support passing structures as parameters in
functions.
return expression;
}
1] PASSING EACH INDIVIDUAL ITEM OF THE STRUCTURE AS A FUNCTION
ARGUMENT: the structure data members will be passed to another function by value. It means
the whole structure is not passed, instead of that data members and their values will be passed as
arguemnets. So, this structure can be accessed from called function.
Union in C Language
What is Union in C Language?
Union is also a user-defined data type, like structure that contains data members of different
data types.
All the members present in the union share the same location, whereas in the structure each
member got separate memory.
In union, more than one member cannot get memory at the same time, so only one member can
contain a value at a time, whereas in structure all the members can contain different values at
the same time.
union union_name
{
//member definitions
Data_Type member1_variable;
Data_Type member2_variable;
Data_Type member3_variable;
…
};
union is a keyword with the help of which we create new data type.
union_name – This is the name of the union data type, you can keep this name as per
your choice like employee, college, item, etc.
DataType – DataType can contain int, char, float, double anything.
member1_variable – This is the name of the variable. Every element located inside the
union is called a member.
Example -:
union item
{ int x;
float y;
char z;
};
Note -: The size of the union is equal to the size of the largest data member of the union. For
example – If a union has a union member of 1, 2, 4, 8 bytes, then the size of the union will be 8
bytes.
Example -:
union item
{ int x;
float y;
char z;
};
Here union is the keyword and item is a new user-defined data type inside which with the help
of int, float, and char there are three union members declared as x, y, and z. If we want to access
these three members then for this we have to declare a variable of this item data type.
#include<stdio.h>
union item
{ int x;
float y;
char z;
};
void main()
{
union item it1, it2;
}
As I mentioned above, to access the union member, we have to declare the union variable. So
here in this example, we have used union item it1, it2; in the main() function to access union
members. By declaring two union variables named it1, and it2, with the help of which we can
easily access the union member.
Method 2 -: At the end of the union while defining union.
Let’s understand this also through an example -:
Example -:
union item
{ int x;
float y;
char z;
}it1,it2;
We can also declare the union variable like in the above example.
The dot (.) operator is used to access the union member and if any union pointer variable
wants to access the union member then -> (structure pointer operator) is used instead of
the dot (.) operator.
it1.x = 35;
it1.z = 'a';
it1.y = 15.5;
}
Accessing Members in Union
Like structure, we can also access the union member in these two ways. Let’s learn about these
methods.
Examples -:
#include<stdio.h>
union item
{ int x;
float y;
};
void main()
{
union item it1;
it1.x = 10;
it1.y = 15.5;
Output -:
x = 10
y = 15.5
it1.z = 'a';
it1.y = 15.5;
Output -:
x = y = 15. 5
In this example, we wanted to print the stored values in x and y to the screen by accessing x and
y simultaneously. But it did not happen. The compiler was able to print only the value stored in y
because, as I mentioned above, in a union we can access only one union member at a time.
In the earlier example, we had accessed both the members separately and printed their values
in the screen, so the output was absolutely correct.
Note -: If union variable is a pointer then we can access more than one member at a time.
Let’s now learn about the other way to access union member
// p2 is a pointer to union p1
union test* p2 = &p1;
Output -:
65 A
In this example, we created two pointer variables p1, and p2, and used -> to access union
members by pointer variable. Since the ASCII value of 65 is A, the result will print the value of p1
as 65 and the value of p2 as A.
Union members use the same memory location to store data among themselves. Union is very
useful in embedded programming.
Advantages of Union
It takes very less memory space than the structure
Using union, you can only access the last member directly.
Unions are more useful when you need to store the values of multiple data members at the same
time, sharing the same memory location.
Its size is equal to the size of the largest union member.
Disadvantages of Union
Only one member can be accessed at a time.
More than one union member cannot be used simultaneously.
A memory location is shared between more than one union member.
Structure Union
The struct keyword is used to The union keyword is used to
define a structure. define union.
Each struct member gets a
All Unio members get only one
different memory location to store
memory location to store data
the data
Changing the value of one data
A change in one data member
member does not affect the other
affects other members.
data member.
You can initialize the value by You can initialize the value by
accessing more than one member accessing only one member at a
at a time. time.
The size of the structure is the The size of the union is equal to
sum of the size of the structure the size of the largest member in
member. the union.
Each struct member gets space in Not every union member gets
memory. space in memory.
It supports flexible array It does not support flexible array
Can access more than one Only one member can be
member at a time. accessed at a time.
Enum or Enumeration
The enum keyword is used to define enumeration. Its basic syntax is something like this –
Basic Syntax of enum in C language,
enum enum_name {const1, const2, const3....... };
Here enum is a keyword with the help of which we are defining a new data type.
enum_name is the name of the new data type. You can keep this name as per your wish.
The value of const1 is 0 by default and after that the value of const2, const3 goes on doing 1, 2,
3 like this, you can change these by default values at the time of declaration only if needed.
Example -:
// Changing default values of enum constants
enum month { jan = 1, feb, march ....... };
#include<stdio.h>
enum month
{ January, February, March, April, May, June, July, August, September, October, November, December
};
void main()
{
enum month m1, m2;
}
enum month
{ January, February, March, April, May, June, July, August, September, October, November, December
}m1, m2;
Note -: In enum variable, we can assign or store only one value at a time.
Example -:
#include<stdio.h>
enum month
{ January = 1, February, March, April, May, June, July, August, September, October, November, December
};
void main()
{
enum month m1, m2;
m1 = January;
m2 = February;
printf("Month %d", m1);
printf("\nMonth %d", m2);
}
In this example, we have created a new data type named month which holds the details
of all the months. Since enum variables can store only one value, by assigning January
to m1 and February to m2, the values of m1 and m2 are printed by the printf function.
Output -: Month 1
Month 2
An enum is used to store a value, that can never change, such as month names, seven
days of the week, true, false, etc.
Example -:
#include<stdio.h>
enum boolean
{ false , true
}result;
void main()
{
int x;
printf("Enter a number ");
scanf("%d", &x);
if(x%2==0)
result = true;
else
result = false;
if (result)
printf("Even Number");
else
printf("Odd Number");
}
In this example, we created a boolean and created an enum variable named result. In this
program, we took a value from the user and applied an if condition to find out whether this
value is an odd number or an even number, and assigned the result to the result variable.
According to whatever value came in this result variable, we printed that result on the
screen.
Output -:
Enter a number
15
Even number
:Definitions
File: A file is defined as a collection of data stored on the secondary device such as hard
disk. FILE is type defined structure and it is defined in a header file “stdio.h”. FILE is a
derived data type. FILE is not a basic data type in C language.
Input File: An input file contains the same items that might have typed in from
the keyboard.
Output File: An output file contains the same information that might have been
sent to the screen as the output from the program.
Text(data) File:A text file is the one where data is stored as a stream of characters
that can be processed sequentially.
Like all the variables are declared before they are used, a file pointer variable
should be declared.
FILE *fp;
Example:
#include <stdio.h>
void main()
{
FILE *fp; /* Here, fp is a pointer to a structure FILE */
---------------------------
-------------------------
}
Page 1
2. File open Function
The file should be opened before reading a file or before writing into a file.
Syntax:
fopen() function will return the starting address of opened file and it is stored in
file pointer.
If file is not opened then fopen function returns NULL
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
Modes of File
Mode Meaning
“r” opens a text file for reading. The file must exist.
“w” creates an text file for writing.
“a” Append to a text file.
1. Read Mode(“r”)
This mode is used for opening an existing file to perform read operation.
The various features of this mode are
Used only for text file
If the file does not exist, an error is returned
The contents of the file are not lost
The file pointer points to beginning of the file.
Page 2
File position after opening
File contents
EOF(End of File)
2. Write Mode(“w”)
This mode is used to create a file for writing.
The various features of this mode are
If file does not exist, a new file is created.
If a file already exists with the same name, the contents of the file are erased and
the file is considered as a new empty file.
The file pointer points to the beginning of the file.
EOF(End of File)
3. Append Mode(“a”)
This mode is used to insert the data at the end of the existing file.
The various features of this mode are
Used only for text file.
If the file already exist, the file pointer points to end of the file.
Page 3
If the file is does not exist. A new file is created.
Existing data cannot be modified.
File contents
EOF(End of File)
Examples
Read Mode Write Mode
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp // File Pointer
FILE *fp // File Pointer fp=fopen(“ecb.txt”,”w”); //opening file ecb in writemode
fp=fopen(“civil.txt”,”r”);//opening file civil in readmode
if (fp == NULL) //file does not exist
if (fp == NULL) //file does not exist {
{ printf(“Error in opening the file\n”);//error message
printf(“Error in opening the file\n”);//error message exit(0); //terminate the program
exit(0); //terminate the program }
} fclose(fp); // close the file ecb.txt
fclose(fp); // close the file civil.txt }
}
Page 4
Append Mode
#include<stdio.h>
void main()
{
Page 5
3. Closing a file
When we no longer need a file, that file should be closed.
This is the last operation to be performed on a file.
A file can be closed using fclose() function.
If a file is closed successfully, 0 is returned, otherwise EOF is returned.
Syntax:
fclose(file pointer);
Example:
fclose(fp);
Syntax:
fscanf(fp, “format string”, address list);
where,
“fp” is a file pointer. It points to a file from where data is read.
“format String”: The data is read from file and is stored in variable s specified in the list ,will
take the values from the specified pointer fp by using the specification provided in format sting.
“address list”: address list of variables.
Page 6
Example:
FILE *fp FILE *fp
fp=fopen(“name.txt”,”r”); fp=fopen(“marks.txt”,”r”);
fscanf(“fp,”%s”,name); fscanf(“fp,”%d%d%d”,&m1,&m2,&m3);
Note:
1. If the data is read from the keyboard then use stdin in place of fp
2. If the data is read from the file then use fp
2.fprintf():
The function fprintf is used to write data into the file.
Syntax:
fprintf(fp, “format string”, variable list);
where,
“fp” is a file pointer.It points to a file where data to be print.
“format String”: group of format specifiers.
“address list”:list of variables to be written into file
Example:
FILE *fp FILE *fp
fp=fopen(“name.txt”,”w”); fp=fopen(“marks.txt”,”w”);
fscanf(“fp,”%s”,name); fscanf(“fp,”%d%d%d”,m1,m2,m3);
Note:
1. If the data has to be printer on output screen then use stdout in place of fp
2. If the data has to be written to the file then use fp
Page 7
Example Program
Write a C program to read the contents of two files called as name.txt and usn.text and
merge the contents to another file called as output.txt and display the contents on console
using fscanf() and fprintf().
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char name[20];
int usn;
fp1=fopen("name.txt","r");
fp2=fopen("usn.txt","r");
fp3=fopen("output.txt","w");
for(;;)
{
if(fscanf(fp1,"%s",name)>0)
{
if(fscanf(fp2,"%d",&usn)>0)
{
fprintf(fp3,"%s %d\n",name,usn);
}
else break;
}
else break;
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
fp3=fopen("output.txt","r");
printf("NAME\tUSN\n");
while(fscanf(fp3,"%s %d\n",name, &usn)>0)
{
printf("%s \t%d\n",name,usn);
}
fclose(fp3);
}
Page 8
File I/O functions for fgets() and fputs()
1.fgets()
fgets() is used to read a string from file and store in memory.
Syntax:
ptr=fgets(str,n,fp);
where
fp ->file pointer which points to the file to be read
str ->string variable where read string will be stored
n ->number of characters to be read from file
ptr->If the operation is successful, it returns a pointer to the string read in.
Otherwise it returns NULL.
The returned value is copied into ptr.
Example:
FILE *fp; 1024fp 1024 a.txt 1048
char s[10]; SVITPCD s
SVIT
char *ptr;
fp=fopen(“a.txt”,”r”);
ptr
if(fp==NULL)
1048
{
printf(“file cnnnot be opened);
exit(0);
}
ptr=fgets(s,4,fp);
fclose(fp);
Example Programs:
1.Write a C program to read from file using 1.Write a C program to read string from keyboard
functionfgets. usingfunction fgets.
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp; char str[15];
char str[15]; char *ptr;
char *ptr; printf(“Enter the string”);
fp=fopen(“name.txt”,”r”): ptr=fgets(str,10,stdin);
if(fp==NULL) if(ptr==NULL)
{ {
printf(“file cannot be opened”); printf(“reading is unsuccessful”);
exit(0); exit(0);
Page 9
} }
ptr=fgets(str,10,fp); printf(“string is”);
if(ptr==NULL) puts(str);
{ fclose(fp);
printf(“reading is unsuccessful”); }
exit(0);
}
printf(“string is”);
puts(str);
fclose(fp);
}
2.fputs()
fputs() is used to write a string into file.
Syntax:
fputs(str,fp);
where
fp ->file pointer which points to the file to be read
str ->string variable where read string will be stored
Example:
FILE *fp,*fp1; 1024 fp 1024 a.txt 1048
char s[10]; SVITPCD s
SVIT
char *ptr;
fp=fopen(“a.txt”,”r”);
fp1=fopen(“b.txt”,”w”); ptr 1048
if(fp==NULL)
{ b.txt
printf(“file cnnnot be opened); SVIT
exit(0);
}
ptr=fgets(s,4,fp);
fputs(s,fp1);
fclose(fp);
fclose(fp1);
Example Program:
1.Write a C program to read from file using function fgets and print into file using fputs
function.
#include<stdio.h>
void main()
{
Page 10
FILE *fp,fp1;
char str[15];
char *ptr;
fp=fopen(“name.txt”,”r”);
fp1=fopen(“output.txt”,”w”);
if(fp==NULL)
{
printf(“file cannot be opened”);
exit(0);
}
ptr=fgets(str,10,fp);
if(ptr==NULL)
{
printf(“reading is unsuccessful”);
exit(0);
}
fputs(str,fp1);
fclose(fp);
fclose(fp1);
}
1.fgetc()
fgetc() function is used to read a character from file and store it in memory.
Syntax:
ch=fgetc(fp);
Example 1:
FILE *fp;
fp=fopen(“sec.txt”,”r”);
ch=fgetc(fp);
Example 2:
FILE *fp; 1024fp 1024 a.txt
char ch; B ch B
fp=fopen(“a.txt”,”r”);
ch=fgets(fp);
fclose(fp);
Page 11
3.fputc()
fgetc() function is used to write a character into a file.
Syntax:
fputc(ch,fp);
Example 1:
FILE *fp;
fp=fopen(“sec.txt”,”w”);
fputc(ch,fp);
Example 2:
FILE *fp,*fp1; 1024 fp 1024 a.txt 1048
char ch; SVITPCD s
SVIT
fp=fopen(“a.txt”,”r”);
fp1=fopen(“b.txt”,”w”); ptr
ch=fges(fp); b.txt
fputc(ch,fp1); SVIT
fclose(fp);
fclose(fp1);
Example Programs
Write a C program to copy one file to another using Write a C program to concatenate two filesusing
fgetc() and fputc() functions. fgetc() and fputc() functions.
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
FILE *fp1,*fp2; FILE *fp1,*fp2,*fp3;
char ch; char ch;
fp1=fopen(“file1.txt”,”r”); fp1=fopen(“file1.txt”,”r”);
fp2=fopen(“file2.txt”,”w”); fp2=fopen(“file2.txt”,”r”);
while((ch=fegtc(fp1))!=EOF) fp3=fopen(“file3.txt”,”w”);
{
fputc(ch,fp2); while((ch=fegtc(fp1))!=EOF)
} {
fclose(fp1); fputc(ch,fp3);
fclose(fp2); }
}
Page 12
while((ch=fegtc(fp2))!=EOF)
{
fputc(ch,fp3);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
Write a C program for counting the characters, blanks, tabs and lines in file.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int cc=0,bc=0,tc=0,lc=0;
fp1=fopen(“file1.txt”,”r”);
while((ch=fegtc(fp1))!=EOF)
{
cc++;
if(ch==’ ’) bc++;
if(ch==’ \n’) lc++;
if(ch==’\t ’) tc++;
}
fclose(fp);
printf(“total number of characters=%d\n”,cc);
printf(“total number of tabs=%d\n”,tc);
printf(“total number of lines=%d\n”,lc);
printf(“total number of blanks=%d\n”,bc);
}
Page 13
Write a program to read data from the keyboard/input stream and write it into a file
called data.txt. Also, read the same data from the file and display it on the screen/output stream.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fp;
char str[200];
fp= fopen("data.txt","w");
if(fp == NULL)
{
printf("error");
exit(1);
}
printf("enter the string");
gets(str);
fprintf(fp, "%s",str);
fscanf(fp, "%s",str);
printf("%s",str);
fclose(fp);
}
Example:
In MS_DOS command prompt looks as follows:
C:\>copy T1.c T2.c
Page 14
The above copy command copies contents of T1.c to T2.c. In the above line copy, T1.c and
T2.c are called command line arguments.
Write a C program to accept a file either through command line or as specified by
user during runtime and displays the contents.
#include<stdio.h>
#include<string.h>
void main(int argc,char *argv[])
{
FILE *fp;
char fname[10];
char ch;
if(arg==1)
{
printf(“\n Enter file name\n”);
scanf(“%s”,fname);
}
else
{
strcpy(fname, argv[1]);
}
fp=fopen(fname,”r”);
if(fp==NULL)
{
printf(“cannot open file”);
exit(0);
}
printf(“contents of file are\n”);
while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
}
}
Page 15