Unit 5 PDF
Unit 5 PDF
CLR -3: Store and retrieve data in a single and multidimensional array
Utilize custom designed functions that can be used to perform tasks and
CLR -4: can be repeatedly used in any application
Create storage constructs using structure and unions. Create and Utilize
CLR -5: files to store and retrieve information
Create a logical mindset to solve various engineering applications using
CLR -6: programming constructs in C
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
COURSE LEARNING
OUTCOMES (CLO)
At the end of this course, learners will be able to:
Identify methods to solve a problem through computer programming. List
CLO -1: the basic data types and variables in C
Apply the logic operators and expressions. Use loop constructs and
CLO -2: recursion. Use array to store and retrieve data
Analyze programs that need storage and form single and multi-dimensional
CLO -3: arrays. Use preprocessor constructs in C
Create user defined functions for mathematical and other logical operations.
CLO -4: Use pointer to address memory and data
Create structures and unions to represent data constructs. Use files to store
CLO -5: and retrieve data
Apply programming concepts to solve problems. Learn about how C
CLO -6: programming can be effectively used for solutions
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
LEARNING RESOURCES
S. No TEXT BOOKS
4. http://www.c4learn.com/learn-c-programming-language/
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
UNIT V
INTRODUCTION
Initializing Structure, Declaring Structure variable- Structure using
typedef, Accessing members – Nested structure Accessing
elements in a structure array – Array of structure Accessing
elements in a structure array –Passing Array of Structure to
function- Array of Pointers to structures- Bit Manipulation of
structure and pointer to structure – Union Basic and declaration –
Accessing Union Members Pointers to union
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
UNIT V
INTRODUCTION
Dynamic memory allocation, malloc, realloc , free – Allocating
Dynamic Array- Multidimensional array using dynamic
memory allocation- file: opening, defining, closing, File Modes,
File Types- Writing contents into a file – Reading file contents –
Appending an existing file- File permissions and rights-
changing permissions and rights.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
INTRODUCTION TO STRUCTURE
• Problem:
– How to group together a collection of data items
of different types that are logically related to a
particular entity??? (Array)
Solution: Structure
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
STRUCTURE
8
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Defining a Structure
• Syntax:
struct structure_name
{
data_type member_variable1; data_type
member_variable2;
………………………………; data_type member_variableN;
};
Once structure_name is declared as new data type, then variables of that typecan be
declared as:
struct structure_name structure_variable;
Note: The members of a structure do not occupy memory until they are
associated with a structure_variable. 9
• Example
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
struct student st;
• Multiple variables of struct student type can be declared
as:
struct student st1, st2, st3;
10
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Defining a structure…
• Each variable of structure has its own copy of member
variables.
• The member variables are accessed using the dot (.) operator or
memberoperator.
• For example: st1.name is member variable name of st1
structure variable while st3.gender is member variable gender
of st3 structure variable.
11
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Defining a structure…
struct student struct
{ {
char name[20]; char name[20]; int
int roll_no; roll_no; float marks;
float marks; char gender;
char gender; long intphone_no;
long intphone_no; }st1, st2, st3;
}st1, st2, st3;
12
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Structure initialization
• Syntax:
struct structure_name structure_variable={value1, value2, …, valueN};
13
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
};
void main()
{
struct student st1={“ABC", 4, 79.5, 'M', 5010670};
clrscr();
printf("Name\t\t\tRoll No.\tMarks\t\tGender\tPhone No.");
printf("\n.........................................................................\n");
printf("\n %s\t\t %d\t\t %f\t%c\t %ld", st1.name, st1.roll_no, st1.marks,
st1.gender, st1.phone_no);
getch();
}
14
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Partial Initialization
• We can initialize the first few members and leave the
remaining blank.
• However, the uninitialized members should be only at
the end of the list.
• The uninitialized members are assigned default
values as follows:
– Zero for integer and floating point numbers.
– ‘\0’ for characters andstrings.
15
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
void main()
{
struct student s1={“name", 4};
clrscr();
printf("Name=%s", s1.name);
printf("\n Roll=%d", s1.roll);
printf("\n Remarks=%c", s1.remarks);
printf("\n Marks=%f", s1.marks);
getch();
}
16
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Question
• Create a structure named student that has name, roll and
mark as members. Assume appropriate types and size of
member. Write a program using structure to read and display
the data entered by the user.
18
struct student
{
char name[20];
int roll;
float mark;
};
void main()
{
struct student s;
clrscr();
printf("Enter name:\t");
gets(s.name);
printf("\n Enter roll:\t");
scanf("%d", &s.roll);
printf("\n Enter marks:\t");
scanf("%f", &s.mark);
printf("\n Name \t Roll \t Mark\n");
printf("\n...................................\n");
printf("\n%s\t%d\t%f", s.name, s.roll, s.mark);
getch();
}
19
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
22
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Array of structure
• Let us consider we have a structure as:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
• If we want to keep record of 100 students, we have to make 100
structure variables like st1, st2, …,st100.
• In this situation we can use array of structure to store the records of
100 students which is easier and efficient to handle (because loops
can be used).
24
Array of structure…
25
• Write a program that takes roll_no,fname lname of 5
students and prints the same records in ascending order
on the basis of roll_no
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Reading values
for(i=0; i<5; i++)
{
printf("\n Enter roll number:"); scanf("%d",
&s[i].roll_no);
Sorting values
for(i=0; i<5; i++)
{
for(j=i+1; j<5; j++)
{
if(s[i].roll_no<s[j].roll_no)
{
temp = s[i].roll_no;
s[i].roll_no=s[j].roll_no;
s[j].roll_no=temp;
}
}
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Question
• Define a structure of employee having data members
name, address, age and salary. Take the data for n
employees in an array and find the average salary.
• Write a program to read the name, address, and
salary of 5 employees using array of structure.
Display information of each employee in alphabetical
order of theirname.
29
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
for(i=0;i<n;i++)
Reading Values
{
printf("\n Enter information about student%d",i+1); printf("\n
Name:\t");
scanf(" %s", s[i].name); printf("\n
Class:\t"); scanf("%d", &s[i]._class);
printf("\n Section:"); scanf(" %c",
&s[i].section);
printf("\n Input marks of 6subjects:\t"); for(j=0;j<6;j++)
{
scanf("%f", &temp);
s[i].marks[j]=temp;
} } 27
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
36
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
37
struct date
{
int day;
int month;
int year;
};
struct name
{
char first_name[10];
char middle_name[10];
char last_name[10];
};
struct personal_record
{
float salary;
struct date birthday,deathday;
struct name full_name;
};
38
• Create a structure named date that has day, month and year as
its members. Include this structure as a member in another
structure named employee which has name, id and salary as
other members. Use this structure to read and display
employee’s name, id, date of birthday andsalary.
39
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Pointer to Structure
• A structure type pointer variable can be declared as:
struct book
{
char name[20];
int pages; float price;
};
struct book *bptr;
• However, this declaration for a pointer to structure does not allocate any memory for a structure but allocates
only for a pointer, so that to access structure’s members through pointer bptr, we must allocate the memory
using malloc()function.
• Now, individual structure members are accessed as:
bptr->name bptr->pages bptr->price
41
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Pointer to Structure…
• Also, the address of a structure type variable can be stored in a structure type
pointer variableas follows:
struct book
{
char name[20]; int pages;
float price;
};
struct book b,*bptr; bptr=&b;
• Here, the base address of b is assigned tobptr pointer.
42
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Pointer to Structure…
• Now the members of the structure book can
be accessed in 3 ways as:
b.name bptr->name (*bptr).name
b.pages bptr->pages (*bptr).pages
b. price bptr-> price (*bptr).price
43
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Problem
• Define a structure of employee having data members name,
address, age and salary. Take data for n employee in an array
dynamically and find the averagesalary.
• Define a structure of student having data members name,
address, marks in Clanguage, and marks in information system.
Take data for n students in an array dynamically and find the
total marksobtained.
46
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
47
Passing structure member to functions
48
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
display(emp.name,emp.id,emp.salary);
45
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
display(emp);
display(&emp);
Example:
#include<stdio.h>
int main()
{
typedef int Number;
Number num1 = 40,num2 = 20;
Number answer;
answer = num1 + num2;
printf("Answer : %d",answer);
return(0);
}
Output :
Answer : 60
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
• But when we have a pointer of structure type, we use arrow -> to access
structure members.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
• Integer can store 2 bytes (*) , so 2 bytes are manipulated in bits and 1 bit is
reserved for b1. Similarly b2,b3 will get single bit.
• data1.b1
• data1.b2
• data1.b3
• data1.b4
• data1.b5
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
data1.b1 = 1
data1.b2 = 1
data1.b3 = 0
data1.b4 = 10
data1.b5 = 234
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Unions
• 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.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
union car
syntax
{
char name[50];
int price;
};
union car
char name[50];
int price;
OR
union car
char name[50];
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
size of union = 32
size of structure = 40
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Memory allocation
There is difference in memory allocation between union and structure as suggested in below 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.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
output
Enter name Hillary
Enter salary 1234.23
Displaying Name: f%Bary
Salary: 1234.2
Initially, Hillary will be stored in u.name and other members of union
will contain garbage value. But when user enters value of salary,
1234.23 will be stored in u.salary and other members will contain
garbage value. Thus in output, salary is printed accurately but, name
displays some random string.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Accessing Union Members
• To access any member of a union, we use the member access operator (.).
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
output
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got
corrupted because the final value assigned to the variable has
occupied the memory location and this is the reason that the value
of str member is getting printed very well.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Example
• Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having unions
−
#include <stdio.h>
#include <string.h>
union Data
{ int i;
float f;
char str[20];
};
int main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
data.i : 10
output
data.f : 220.500000
data.str : C Programming
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
Dynamic Arrays
• Dynamic arrays are created using pointer variables and memory
management functions malloc,calloc and realloc.
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.
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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)
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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”);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
fscanf()
Syntax:
fscanf (fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(“input.txt”,”r”);
int i;
fscanf (fp,“%d",i);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
getc()
Syntax:
identifier = getc (file pointer);
Example:
FILE *fp;
fp=fopen(“input.txt”,”r”);
char ch;
ch = getc (fp);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
putc()
write a single character to the output file, pointed to by
fp.
Example:
FILE *fp;
char ch;
putc (ch,fp);
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
End of File
• There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by the
fscanf function:
FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.\n”) ;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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.
Example 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;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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.
Example
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;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
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.
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;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
ftell()
offset = ftell( file pointer );
"ftell" returns the current position for input or output on the file
#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;
}
SRM
INSTITUTE OF SCIENCE AND TECHNOLOGY,
CHENNAI.
THANK YOU………