SlideShare a Scribd company logo
1 of 31
Slide 1 of 31Ver. 1.0
Programming in C
In this session, you will learn to:
Work with structures
Use structures in file handling
Objectives
Slide 2 of 31Ver. 1.0
Programming in C
Working with Structures
Structures:
Are collection of heterogeneous data types.
Are also known as records.
Are used to define new data types.
Are defined using the struct keyword.
Slide 3 of 31Ver. 1.0
Programming in C
Defining Structures
A structure is defined by using the struct keyword.
Consider the following example:
struct {
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of_sale;
} salesrec;
All the variables in the record are treated as one data structure –
salesrec.
Slide 4 of 31Ver. 1.0
Programming in C
Practice: 7.1
1. State whether True or False:
The members of a structure must be of the same data type.
1. a. Give the declaration for a structure called date with the
following members.
day (2 digits)
month (2 digits)
year (4 digits)
b. Give appropriate statements to accept values into the
members of the structure date and then print out the
date as mm/dd/yyyy.
Slide 5 of 31Ver. 1.0
Programming in C
Solution:
1. False
2. a. The structure declaration should be:
struct {
int day;
int month;
int year;
} date;
b. The statements could be:
scanf(“%d%d%d”, &date, &date.month, &date.year);
printf(“%d/%d/5d”, date.month, date.day,
date.year);
Practice: 7.1 (Contd.)
Slide 6 of 31Ver. 1.0
Programming in C
Defining a label structures:
Structure label may be declared as:
struct salesdata {
char transno [4];
int salesno;
int prodno;
int unit_sold;
float value_of-sale;
};
struct salesdata salesrec;
Here, salesdata is the label and salesrec is the data item.
Defining Structures (Contd.)
Slide 7 of 31Ver. 1.0
Programming in C
Practice: 7.2
Given the following declarations:
struct date_type{ struct {
int day; int day;
int month; int month;
int year; int year;
}; } date;
Declaration 1 Declaration 2
Answer the following questions:
1. Memory is allocated for the structure (date_type/ date).
2. Which of the following is/are the correct way(s) of referring to
the variable day?
a. day.date
b. date_type.day
Slide 8 of 31Ver. 1.0
Programming in C
Practice: 7.2 (Contd.)
3. What change(s) should be made to the first declaration so that
the structure date is created of type date_type?
4. Is the following statement valid in case of the second
declaration? If not, why?
struct date another_date;
Slide 9 of 31Ver. 1.0
Programming in C
Solution:
1. date (date_type is only a structure type)
2. a. Invalid because the structure name precedes the variable
name.
b. Invalid because date_type is not actually created in
memory, it is only a label.
3. The following statement should be added after the struct
declaration:
struct date_type date;
4. This is invalid because date is not a structure type but an
actual structure in memory.
Practice: 7.2 (Contd.)
Slide 10 of 31Ver. 1.0
Programming in C
Passing Structures to Functions
Passing Structures to Functions:
Structures may be passed to functions either by value or by
reference.
Usually methods pass the address of the structure.
The name of the variable being referenced is preceded by the
symbol .
Slide 11 of 31Ver. 1.0
Programming in C
Practice: 7.3
1. Consider the following code:
struct date_type {
int day;
int month;
int year;
}; struct date_type date, *ptr;
a. How can the pointer variable ptr be assigned the address of
the structure date?
b. Is the following statement valid?
ptr = &date_type;
c. Give alternative ways of referring to:
i. &date.day
ii. date.month
Given that ptr has been assigned the address of the structure
date.
Slide 12 of 31Ver. 1.0
Programming in C
Practice: 7.3 (Contd.)
2. Consider the incomplete code of a program that is given in
the following file. The code uses a function called
printmonth() that displays the month name
corresponding to any month number. The month number is
accepted into the member month of the structure date. The
blanks have to be filled in appropriately.
Microsoft Office
Word 97 - 2003 Document
Slide 13 of 31Ver. 1.0
Programming in C
Solution:
1. a. By using the following statement:
ptr = &date;
b. No. because date_type is not created in memory; it is
only a label.
c. i. &(ptr-> date)
ii. ptr-> month
2. The statement to invoke printmonth() could be:
printmonth(&date); /*invoke printmonth() by
passing structure */
The missing lines in the code for printmonth() are:
printmonth(point)
struct date_type *point;
point is the parameter of the function since it is used within
the function to access members of the structure date.
Practice: 7.3 (Contd.)
Slide 14 of 31Ver. 1.0
Programming in C
Arrays of Structures
Arrays of structures can also be created.
It works in the same way as any other data type array.
Consider the following example:
struct prod data{
char prodname[8];
int no_of_sales;
float tot_sale;
};
An array for the preceding structure can be declared as:
struct proddata prod_field[4];
The elements of the structure can be accessed as:
prod_field [0].prodnam[0];
Slide 15 of 31Ver. 1.0
Programming in C
Practice: 7.4
1. Declare a structure which will contain the following data for
3 employees:
Employee code (3 characters)
First name (20 characters)
Middle initial (1 character)
Last name (20 characters)
The employee codes to be stored in this structure are E01,
E02, and E03.
2. Write the code to input for all 3 employees, and print out the
initials of each (e.g. Ashraf A Kumar would be printed as
AAK) along with their codes.
Slide 16 of 31Ver. 1.0
Programming in C
Solution:
Practice: 7.4 (Contd.)
Microsoft Office
Word 97 - 2003 Document
Slide 17 of 31Ver. 1.0
Programming in C
Working with Structures (Contd.)
A structure can be used as a valid data type within another
structure. For example, if date has been defined as:
struct date{
int dd;
int mm;
int yy;
};
The date structure can be used in another structure as:
struct trans_rec{
char transno[4];
char type;
float amount;
struct date tran_date;
};
Slide 18 of 31Ver. 1.0
Programming in C
Practice: 7.5
1. What will the following declaration do?
typedef char sentence[50];
sentence complex[10];
Slide 19 of 31Ver. 1.0
Programming in C
Solution:
1. The first statement defines sentence as a data type consisting
of an array of 50 characters. The second statement declares
complex as a two-dimensional array, (an array of ten arrays of
50 characters each).
Practice: 7.5 (Contd.)
Slide 20 of 31Ver. 1.0
Programming in C
Using Structures in File Handling
To store data permanently, it needs to be stored in a file.
Mostly, the data, to be written in the file, is a logical group of
information i.e. records.
These records can be stored in structure variables. Hence,
you need to write structures onto a file.
Slide 21 of 31Ver. 1.0
Programming in C
Writing Records onto a File Using Structures
The fwrite() function is used to write structures onto a
file.
The fwrite() function has the following syntax:
fwrite (constant pointer, sizeof (datatype), 1,
FILE pointer);
The first parameter is a pointer to the data to be written.
The second parameter is the size of data to be written.
The third parameter is the number of objects or data to be
written.
The fourth parameter is the pointer to file.
Slide 22 of 31Ver. 1.0
Programming in C
Practice: 7.6
Now that various assets of the transaction data entry
program have been explained, these have to be
consolidated and the entire program coded. The problem
statement is repeated below.
A transaction data entry program called dataent, used at
the familiar Alcatel Automatics Company, has to be coded.
The transaction file stores the data on transactions made by
the salesmen of the company. The records consist of the
following fields.
Transaction number
Salesman number
Product number (numbered 1 to 4)
Units sold
Value of sale
Value of sale is calculated in the program.
Slide 23 of 31Ver. 1.0
Programming in C
Practice: 7.6 (Contd.)
The program should allow the user to indicate when he
wants to stop data entry (i.e. it should keep accepting
records until the user indicates that there are no more
records).
After all records have been entered, a report on the total
number of sales and the total sale value for each product is
to be printed in the following format (for each product).
Product number : ___________________
Product name : ___________________
Total number of sales : ___________________
Total sale value : ___________________
Use the structures salesrec, salesdata, prodata, and
prod_field defined earlier and code for the report printing
within main(). Also use the code provided on page 7.2 and
7.3 in your solution.
Slide 24 of 31Ver. 1.0
Programming in C
Solution:
Practice: 7.6 (Contd.)
Microsoft Office
Word 97 - 2003 Document
Slide 25 of 31Ver. 1.0
Programming in C
Reading Records from Files Using Structures
The fread() function is used to read data from a stream.
The fread() function has the following syntax:
fread (ptr, sizeof, 1, fp);
The first parameter is a pointer to the variable where the data
is to be fetched.
The second parameter is the size of data to be read.
The third parameter is the number of objects or data to be
read.
The fourth parameter is the pointer to file.
Slide 26 of 31Ver. 1.0
Programming in C
Practice: 7.7
1. Is the following statement to read the first 5 records of the
file trans.dat valid?
fread (ptr, (sizeof(salesrec) *5), 1, fp);
If not state why and give the correct statement. No checks
are to be done for an unsuccessful read.
2. Modify the above fread() statement to include an end-of-
file check and also check whether the records have been
read successfully. In case of end-of-file, display the
message:
End-of-file encountered
and in case of other errors, display the message and exit:
Unsuccessful read
In case of a successful read, display the salesman number
and transaction number of each record. Give all the
structure declarations required.
Slide 27 of 31Ver. 1.0
Programming in C
Solution:
Practice: 7.7 (Contd.)
Microsoft Office
Word 97 - 2003 Document
Slide 28 of 31Ver. 1.0
Programming in C
Practice: 7.8
1. Debug the following program called dat.c using the error
listing provided in the following file.
Microsoft Office
Word 97 - 2003 Document
Slide 29 of 31Ver. 1.0
Programming in C
Solution:
1. The solution to this practice will be discussed in class. Work
out your answer.
Practice: 7.8 (Contd.)
Slide 30 of 31Ver. 1.0
Programming in C
Summary
In this session, you learned that:
Records can be defined in C by using structures.
Structure members can be of the same/different data type.
Memory is not reserved when a structure label is declared. A
structure is created when it is declared as a struct of the
same type as the structure label.
A member of a structure can be accessed as follows:
structure-name.member-name
A pointer to a structure can be used to pass a structure to a
function. Using pointers, the structure members are accessed
as follows:
pointer-name->member-name
Arrays of structures can be defined and initialized (if global or
static). To access any member, an index has to be used after
the structure name, as follows:
structure-name [index ].member-name
Slide 31 of 31Ver. 1.0
Programming in C
Summary (Contd.)
The typedef statement can assign names to user-defined
data types. These are treated the same way as data types
provided by C.
The fread() function can read records from a file into a
structure/array of structures. The format of the function is:
fread (pointer, size of structure, number of
objects to be read, file pointer);
The fread() function returns the number of objects read from
the file. It does not return any special value in case of
end-of-file. The feof() function is used in conjunction with
fread() to check for end-of-file.
The fwrite() function can write a structure array of
structures onto a file. All numeric data is written in compressed
form. Usually, fread() and fwrite() are used in
conjunction.

More Related Content

What's hot

Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Faster Interleaved Modular Multiplier Based on Sign Detection
Faster Interleaved Modular Multiplier Based on Sign DetectionFaster Interleaved Modular Multiplier Based on Sign Detection
Faster Interleaved Modular Multiplier Based on Sign DetectionVLSICS Design
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesSami Mut
 
FP305 data structure PAPER FINAL SEM 3
FP305 data structure PAPER FINAL SEM 3FP305 data structure PAPER FINAL SEM 3
FP305 data structure PAPER FINAL SEM 3Syahriha Ruslan
 
Sample quizz test
Sample quizz testSample quizz test
Sample quizz testkasguest
 
J3 Computer Studies (Pre-NECO BECE)
J3 Computer Studies (Pre-NECO BECE)J3 Computer Studies (Pre-NECO BECE)
J3 Computer Studies (Pre-NECO BECE)Ejiro Ejedafeta
 
Bt0062 fundamentals of it model question paper
Bt0062 fundamentals of it model question paperBt0062 fundamentals of it model question paper
Bt0062 fundamentals of it model question paperAnimish Puttu
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesSami Mut
 
Sp 1418794917
Sp 1418794917Sp 1418794917
Sp 1418794917lakshmi r
 
A new reverse engineering approach to
A new reverse engineering approach toA new reverse engineering approach to
A new reverse engineering approach toijseajournal
 

What's hot (15)

Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Faster Interleaved Modular Multiplier Based on Sign Detection
Faster Interleaved Modular Multiplier Based on Sign DetectionFaster Interleaved Modular Multiplier Based on Sign Detection
Faster Interleaved Modular Multiplier Based on Sign Detection
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Pcd201516
Pcd201516Pcd201516
Pcd201516
 
C# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slidesC# Tutorial MSM_Murach chapter-09-slides
C# Tutorial MSM_Murach chapter-09-slides
 
FP305 data structure PAPER FINAL SEM 3
FP305 data structure PAPER FINAL SEM 3FP305 data structure PAPER FINAL SEM 3
FP305 data structure PAPER FINAL SEM 3
 
Cs8251 faq1
Cs8251 faq1Cs8251 faq1
Cs8251 faq1
 
Sample quizz test
Sample quizz testSample quizz test
Sample quizz test
 
J3 Computer Studies (Pre-NECO BECE)
J3 Computer Studies (Pre-NECO BECE)J3 Computer Studies (Pre-NECO BECE)
J3 Computer Studies (Pre-NECO BECE)
 
ListMyPolygons 0.6
ListMyPolygons 0.6ListMyPolygons 0.6
ListMyPolygons 0.6
 
Bt0062 fundamentals of it model question paper
Bt0062 fundamentals of it model question paperBt0062 fundamentals of it model question paper
Bt0062 fundamentals of it model question paper
 
C# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slidesC# Tutorial MSM_Murach chapter-08-slides
C# Tutorial MSM_Murach chapter-08-slides
 
Sp 1418794917
Sp 1418794917Sp 1418794917
Sp 1418794917
 
A new reverse engineering approach to
A new reverse engineering approach toA new reverse engineering approach to
A new reverse engineering approach to
 

Similar to C programming session 13

C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
C programming session 13
C programming session 13C programming session 13
C programming session 13AjayBahoriya
 
C programming session 01
C programming session 01C programming session 01
C programming session 01Vivek Singh
 
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21chinthala Vijaya Kumar
 
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeDeveloping Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeSusanMorant
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperMalathi Senthil
 
Aae oop xp_02
Aae oop xp_02Aae oop xp_02
Aae oop xp_02Niit Care
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsWilliam Olivier
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1karmuhtam
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Open a new project in Visual Studio Community and name it in the form.pdf
Open a new project in Visual Studio Community and name it in the form.pdfOpen a new project in Visual Studio Community and name it in the form.pdf
Open a new project in Visual Studio Community and name it in the form.pdfNathan2rSPeakes
 
Computer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletComputer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletPittock
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentPVS-Studio
 

Similar to C programming session 13 (20)

C programming session 09
C programming session 09C programming session 09
C programming session 09
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
 
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeDeveloping Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
 
CBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question PaperCBSE Grade12, Computer Science, Sample Question Paper
CBSE Grade12, Computer Science, Sample Question Paper
 
Aae oop xp_02
Aae oop xp_02Aae oop xp_02
Aae oop xp_02
 
Intro
IntroIntro
Intro
 
Notes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculationsNotes how to work with variables, constants and do calculations
Notes how to work with variables, constants and do calculations
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
C programming part2
C programming part2C programming part2
C programming part2
 
C programming part2
C programming part2C programming part2
C programming part2
 
C programming part2
C programming part2C programming part2
C programming part2
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Vb6.0 intro
Vb6.0 introVb6.0 intro
Vb6.0 intro
 
Express 070 536
Express 070 536Express 070 536
Express 070 536
 
Open a new project in Visual Studio Community and name it in the form.pdf
Open a new project in Visual Studio Community and name it in the form.pdfOpen a new project in Visual Studio Community and name it in the form.pdf
Open a new project in Visual Studio Community and name it in the form.pdf
 
Computer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutletComputer systems architecture assignment/tutorialoutlet
Computer systems architecture assignment/tutorialoutlet
 
Lesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignmentLesson 21. Pattern 13. Data alignment
Lesson 21. Pattern 13. Data alignment
 

More from Vivek Singh

C programming session 14
C programming session 14C programming session 14
C programming session 14Vivek Singh
 
C programming session 11
C programming session 11C programming session 11
C programming session 11Vivek Singh
 
C programming session 10
C programming session 10C programming session 10
C programming session 10Vivek Singh
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Vivek Singh
 
C programming session 07
C programming session 07C programming session 07
C programming session 07Vivek Singh
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Vivek Singh
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Vivek Singh
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Vivek Singh
 
C programming session 16
C programming session 16C programming session 16
C programming session 16Vivek Singh
 
Niit aptitude question paper
Niit aptitude question paperNiit aptitude question paper
Niit aptitude question paperVivek Singh
 
Excel shortcut and tips
Excel shortcut and tipsExcel shortcut and tips
Excel shortcut and tipsVivek Singh
 
Sql where clause
Sql where clauseSql where clause
Sql where clauseVivek Singh
 
Sql update statement
Sql update statementSql update statement
Sql update statementVivek Singh
 
Sql tutorial, tutorials sql
Sql tutorial, tutorials sqlSql tutorial, tutorials sql
Sql tutorial, tutorials sqlVivek Singh
 
Sql select statement
Sql select statementSql select statement
Sql select statementVivek Singh
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimizationVivek Singh
 
Sql query tips or query optimization
Sql query tips or query optimizationSql query tips or query optimization
Sql query tips or query optimizationVivek Singh
 
Sql order by clause
Sql order by clauseSql order by clause
Sql order by clauseVivek Singh
 

More from Vivek Singh (20)

C programming session 14
C programming session 14C programming session 14
C programming session 14
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
C programming session 07
C programming session 07C programming session 07
C programming session 07
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
 
Niit aptitude question paper
Niit aptitude question paperNiit aptitude question paper
Niit aptitude question paper
 
Excel shortcut and tips
Excel shortcut and tipsExcel shortcut and tips
Excel shortcut and tips
 
Sql where clause
Sql where clauseSql where clause
Sql where clause
 
Sql update statement
Sql update statementSql update statement
Sql update statement
 
Sql tutorial, tutorials sql
Sql tutorial, tutorials sqlSql tutorial, tutorials sql
Sql tutorial, tutorials sql
 
Sql subquery
Sql subquerySql subquery
Sql subquery
 
Sql select statement
Sql select statementSql select statement
Sql select statement
 
Sql rename
Sql renameSql rename
Sql rename
 
Sql query tuning or query optimization
Sql query tuning or query optimizationSql query tuning or query optimization
Sql query tuning or query optimization
 
Sql query tips or query optimization
Sql query tips or query optimizationSql query tips or query optimization
Sql query tips or query optimization
 
Sql order by clause
Sql order by clauseSql order by clause
Sql order by clause
 

Recently uploaded

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxElton John Embodo
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 

Recently uploaded (20)

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 

C programming session 13

  • 1. Slide 1 of 31Ver. 1.0 Programming in C In this session, you will learn to: Work with structures Use structures in file handling Objectives
  • 2. Slide 2 of 31Ver. 1.0 Programming in C Working with Structures Structures: Are collection of heterogeneous data types. Are also known as records. Are used to define new data types. Are defined using the struct keyword.
  • 3. Slide 3 of 31Ver. 1.0 Programming in C Defining Structures A structure is defined by using the struct keyword. Consider the following example: struct { char transno [4]; int salesno; int prodno; int unit_sold; float value_of_sale; } salesrec; All the variables in the record are treated as one data structure – salesrec.
  • 4. Slide 4 of 31Ver. 1.0 Programming in C Practice: 7.1 1. State whether True or False: The members of a structure must be of the same data type. 1. a. Give the declaration for a structure called date with the following members. day (2 digits) month (2 digits) year (4 digits) b. Give appropriate statements to accept values into the members of the structure date and then print out the date as mm/dd/yyyy.
  • 5. Slide 5 of 31Ver. 1.0 Programming in C Solution: 1. False 2. a. The structure declaration should be: struct { int day; int month; int year; } date; b. The statements could be: scanf(“%d%d%d”, &date, &date.month, &date.year); printf(“%d/%d/5d”, date.month, date.day, date.year); Practice: 7.1 (Contd.)
  • 6. Slide 6 of 31Ver. 1.0 Programming in C Defining a label structures: Structure label may be declared as: struct salesdata { char transno [4]; int salesno; int prodno; int unit_sold; float value_of-sale; }; struct salesdata salesrec; Here, salesdata is the label and salesrec is the data item. Defining Structures (Contd.)
  • 7. Slide 7 of 31Ver. 1.0 Programming in C Practice: 7.2 Given the following declarations: struct date_type{ struct { int day; int day; int month; int month; int year; int year; }; } date; Declaration 1 Declaration 2 Answer the following questions: 1. Memory is allocated for the structure (date_type/ date). 2. Which of the following is/are the correct way(s) of referring to the variable day? a. day.date b. date_type.day
  • 8. Slide 8 of 31Ver. 1.0 Programming in C Practice: 7.2 (Contd.) 3. What change(s) should be made to the first declaration so that the structure date is created of type date_type? 4. Is the following statement valid in case of the second declaration? If not, why? struct date another_date;
  • 9. Slide 9 of 31Ver. 1.0 Programming in C Solution: 1. date (date_type is only a structure type) 2. a. Invalid because the structure name precedes the variable name. b. Invalid because date_type is not actually created in memory, it is only a label. 3. The following statement should be added after the struct declaration: struct date_type date; 4. This is invalid because date is not a structure type but an actual structure in memory. Practice: 7.2 (Contd.)
  • 10. Slide 10 of 31Ver. 1.0 Programming in C Passing Structures to Functions Passing Structures to Functions: Structures may be passed to functions either by value or by reference. Usually methods pass the address of the structure. The name of the variable being referenced is preceded by the symbol .
  • 11. Slide 11 of 31Ver. 1.0 Programming in C Practice: 7.3 1. Consider the following code: struct date_type { int day; int month; int year; }; struct date_type date, *ptr; a. How can the pointer variable ptr be assigned the address of the structure date? b. Is the following statement valid? ptr = &date_type; c. Give alternative ways of referring to: i. &date.day ii. date.month Given that ptr has been assigned the address of the structure date.
  • 12. Slide 12 of 31Ver. 1.0 Programming in C Practice: 7.3 (Contd.) 2. Consider the incomplete code of a program that is given in the following file. The code uses a function called printmonth() that displays the month name corresponding to any month number. The month number is accepted into the member month of the structure date. The blanks have to be filled in appropriately. Microsoft Office Word 97 - 2003 Document
  • 13. Slide 13 of 31Ver. 1.0 Programming in C Solution: 1. a. By using the following statement: ptr = &date; b. No. because date_type is not created in memory; it is only a label. c. i. &(ptr-> date) ii. ptr-> month 2. The statement to invoke printmonth() could be: printmonth(&date); /*invoke printmonth() by passing structure */ The missing lines in the code for printmonth() are: printmonth(point) struct date_type *point; point is the parameter of the function since it is used within the function to access members of the structure date. Practice: 7.3 (Contd.)
  • 14. Slide 14 of 31Ver. 1.0 Programming in C Arrays of Structures Arrays of structures can also be created. It works in the same way as any other data type array. Consider the following example: struct prod data{ char prodname[8]; int no_of_sales; float tot_sale; }; An array for the preceding structure can be declared as: struct proddata prod_field[4]; The elements of the structure can be accessed as: prod_field [0].prodnam[0];
  • 15. Slide 15 of 31Ver. 1.0 Programming in C Practice: 7.4 1. Declare a structure which will contain the following data for 3 employees: Employee code (3 characters) First name (20 characters) Middle initial (1 character) Last name (20 characters) The employee codes to be stored in this structure are E01, E02, and E03. 2. Write the code to input for all 3 employees, and print out the initials of each (e.g. Ashraf A Kumar would be printed as AAK) along with their codes.
  • 16. Slide 16 of 31Ver. 1.0 Programming in C Solution: Practice: 7.4 (Contd.) Microsoft Office Word 97 - 2003 Document
  • 17. Slide 17 of 31Ver. 1.0 Programming in C Working with Structures (Contd.) A structure can be used as a valid data type within another structure. For example, if date has been defined as: struct date{ int dd; int mm; int yy; }; The date structure can be used in another structure as: struct trans_rec{ char transno[4]; char type; float amount; struct date tran_date; };
  • 18. Slide 18 of 31Ver. 1.0 Programming in C Practice: 7.5 1. What will the following declaration do? typedef char sentence[50]; sentence complex[10];
  • 19. Slide 19 of 31Ver. 1.0 Programming in C Solution: 1. The first statement defines sentence as a data type consisting of an array of 50 characters. The second statement declares complex as a two-dimensional array, (an array of ten arrays of 50 characters each). Practice: 7.5 (Contd.)
  • 20. Slide 20 of 31Ver. 1.0 Programming in C Using Structures in File Handling To store data permanently, it needs to be stored in a file. Mostly, the data, to be written in the file, is a logical group of information i.e. records. These records can be stored in structure variables. Hence, you need to write structures onto a file.
  • 21. Slide 21 of 31Ver. 1.0 Programming in C Writing Records onto a File Using Structures The fwrite() function is used to write structures onto a file. The fwrite() function has the following syntax: fwrite (constant pointer, sizeof (datatype), 1, FILE pointer); The first parameter is a pointer to the data to be written. The second parameter is the size of data to be written. The third parameter is the number of objects or data to be written. The fourth parameter is the pointer to file.
  • 22. Slide 22 of 31Ver. 1.0 Programming in C Practice: 7.6 Now that various assets of the transaction data entry program have been explained, these have to be consolidated and the entire program coded. The problem statement is repeated below. A transaction data entry program called dataent, used at the familiar Alcatel Automatics Company, has to be coded. The transaction file stores the data on transactions made by the salesmen of the company. The records consist of the following fields. Transaction number Salesman number Product number (numbered 1 to 4) Units sold Value of sale Value of sale is calculated in the program.
  • 23. Slide 23 of 31Ver. 1.0 Programming in C Practice: 7.6 (Contd.) The program should allow the user to indicate when he wants to stop data entry (i.e. it should keep accepting records until the user indicates that there are no more records). After all records have been entered, a report on the total number of sales and the total sale value for each product is to be printed in the following format (for each product). Product number : ___________________ Product name : ___________________ Total number of sales : ___________________ Total sale value : ___________________ Use the structures salesrec, salesdata, prodata, and prod_field defined earlier and code for the report printing within main(). Also use the code provided on page 7.2 and 7.3 in your solution.
  • 24. Slide 24 of 31Ver. 1.0 Programming in C Solution: Practice: 7.6 (Contd.) Microsoft Office Word 97 - 2003 Document
  • 25. Slide 25 of 31Ver. 1.0 Programming in C Reading Records from Files Using Structures The fread() function is used to read data from a stream. The fread() function has the following syntax: fread (ptr, sizeof, 1, fp); The first parameter is a pointer to the variable where the data is to be fetched. The second parameter is the size of data to be read. The third parameter is the number of objects or data to be read. The fourth parameter is the pointer to file.
  • 26. Slide 26 of 31Ver. 1.0 Programming in C Practice: 7.7 1. Is the following statement to read the first 5 records of the file trans.dat valid? fread (ptr, (sizeof(salesrec) *5), 1, fp); If not state why and give the correct statement. No checks are to be done for an unsuccessful read. 2. Modify the above fread() statement to include an end-of- file check and also check whether the records have been read successfully. In case of end-of-file, display the message: End-of-file encountered and in case of other errors, display the message and exit: Unsuccessful read In case of a successful read, display the salesman number and transaction number of each record. Give all the structure declarations required.
  • 27. Slide 27 of 31Ver. 1.0 Programming in C Solution: Practice: 7.7 (Contd.) Microsoft Office Word 97 - 2003 Document
  • 28. Slide 28 of 31Ver. 1.0 Programming in C Practice: 7.8 1. Debug the following program called dat.c using the error listing provided in the following file. Microsoft Office Word 97 - 2003 Document
  • 29. Slide 29 of 31Ver. 1.0 Programming in C Solution: 1. The solution to this practice will be discussed in class. Work out your answer. Practice: 7.8 (Contd.)
  • 30. Slide 30 of 31Ver. 1.0 Programming in C Summary In this session, you learned that: Records can be defined in C by using structures. Structure members can be of the same/different data type. Memory is not reserved when a structure label is declared. A structure is created when it is declared as a struct of the same type as the structure label. A member of a structure can be accessed as follows: structure-name.member-name A pointer to a structure can be used to pass a structure to a function. Using pointers, the structure members are accessed as follows: pointer-name->member-name Arrays of structures can be defined and initialized (if global or static). To access any member, an index has to be used after the structure name, as follows: structure-name [index ].member-name
  • 31. Slide 31 of 31Ver. 1.0 Programming in C Summary (Contd.) The typedef statement can assign names to user-defined data types. These are treated the same way as data types provided by C. The fread() function can read records from a file into a structure/array of structures. The format of the function is: fread (pointer, size of structure, number of objects to be read, file pointer); The fread() function returns the number of objects read from the file. It does not return any special value in case of end-of-file. The feof() function is used in conjunction with fread() to check for end-of-file. The fwrite() function can write a structure array of structures onto a file. All numeric data is written in compressed form. Usually, fread() and fwrite() are used in conjunction.

Editor's Notes

  1. Begin the session by explaining the objectives of the session.
  2. Discuss the need for structures. Compare structure with an array.
  3. Use this slide to test the student’s understanding on defining structures.
  4. Discuss the advantages of using a label in defining a structure. Tell the students that a structure variable can be directly assigned to another structure variable of the same type. You need not to copy elements individually.
  5. Use this slide to test the student’s understanding on defining structures.
  6. Tell the students that structures can be passed to other functions. The structures can be passed either by value or by reference.
  7. Use this slide to test the student’s understanding on passing structures to functions.
  8. Use this slide to test the student’s understanding on array of structures.
  9. Tell the students the way to access the elements of a structure, which is contained in another structure. Also, discuss the use of the typedef statement.
  10. Use this slide to test the student’s understanding on typedef statement.
  11. Use this slide to test the student’s understanding on the fwrite() function.
  12. Tell the students that they can use the feof() function to check for the end of file. The feof () function does not report end-of-file unless we try to read past the last character of the file. Consider the following code. while (!feof (fp)) { fread (&buf, sizeof (struct buf) , 1 , fp) ; printf (…) ; /* print data from structure */ } Once the last record is read , the feof () function does not return a non-zero value. It senses the end-of-file only after the next read which fails. The buffer buf would still contain the contents of the last record which will be printed again. An alternative would be: while (1) { fread (&buf , sizeof (struct buf) , 1 , fp) ; if (! feof ()) printf (…) ; /* print data from structure */ }
  13. Use this slide to test the student’s understanding on the fwrite() and fread() function.
  14. Use this slide to test the student’s understanding on reading and writing structures in a file.
  15. Use this and the next slide to summarize the session.