SlideShare a Scribd company logo
In this session, you will learn to: Work with structures Use structures in file handling Objectives
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. Working with 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 . Defining Structures
State whether True or False: The members of a structure must be of the same data type. 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. Practice: 7.1
Solution: False 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.)
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.)
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: Memory is allocated for the structure ( date_type/ date ). Which of the following is/are the correct way(s) of referring to the variable day? a. day.date b. date_type.day Practice: 7.2
What change(s) should be made to the first declaration so that the structure date is created of type  date_type ? Is the following statement valid in case of the second declaration? If not, why? struct date another_date; Practice: 7.2 (Contd.)
Solution: date (date_type is only a structure type) 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.)
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   . Passing Structures to Functions
Consider the following code: struct date_type  { int day; int month;  int year; }; struct date_type date,  *ptr; How can the pointer variable  ptr  be assigned the address of the structure  date ? 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. Practice: 7.3
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. Practice: 7.3 (Contd.)
Solution: 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.)
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];  Arrays of Structures
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. Practice: 7.4
Solution: Practice: 7.4 (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;   }; Working with Structures (Contd.)
What will the following declaration do? typedef char sentence[50]; sentence complex[10]; Practice: 7.5
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.)
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. Using Structures in File Handling
The  fwrite()  function is used to write structures onto a file.   The  f write()  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. Writing Records onto a File Using Structures
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. Practice: 7.6
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. Practice: 7.6 (Contd.)
Solution:  Practice: 7.6 (Contd.)
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. Reading Records from Files Using Structures
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. Practice: 7.7
Solution: Practice: 7.7 (Contd.)
Debug the following program called  dat.c  using the error listing provided in the following file. Practice: 7.8
Solution: The solution to this practice will be discussed in class. Work out your answer. Practice: 7.8 (Contd.)
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 Summary
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. Summary (Contd.)
Ad

More Related Content

What's hot (20)

Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Programming construction tools
Programming construction toolsProgramming construction tools
Programming construction tools
sunilchute1
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
Sudheer Kiran
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
Anil Dutt
 
Structures-2
Structures-2Structures-2
Structures-2
arshpreetkaur07
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 
Computer
ComputerComputer
Computer
Hanaa Ahmed
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
Maria Stella Solon
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
Prof. Dr. K. Adisesha
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
Andrew Raj
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 
Strings-Computer programming
Strings-Computer programmingStrings-Computer programming
Strings-Computer programming
nmahi96
 
Computer programming(CP)
Computer programming(CP)Computer programming(CP)
Computer programming(CP)
nmahi96
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi96
 
Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
arshpreetkaur07
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
Programming construction tools
Programming construction toolsProgramming construction tools
Programming construction tools
sunilchute1
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
Sudheer Kiran
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
Anil Dutt
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
K Durga Prasad
 
Cpu-fundamental of C
Cpu-fundamental of CCpu-fundamental of C
Cpu-fundamental of C
Suchit Patel
 
C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013C faqs interview questions placement paper 2013
C faqs interview questions placement paper 2013
srikanthreddy004
 
C interview-questions-techpreparation
C interview-questions-techpreparationC interview-questions-techpreparation
C interview-questions-techpreparation
Kushaal Singla
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
Andrew Raj
 
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdfUSER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
USER DEFINED FUNCTIONS IN C MRS.SOWMYA JYOTHI.pdf
SowmyaJyothi3
 

Viewers also liked (9)

Session no 4
Session no 4Session no 4
Session no 4
Saif Ullah Dar
 
Java script session 3
Java script session 3Java script session 3
Java script session 3
Saif Ullah Dar
 
Session No1
Session No1 Session No1
Session No1
Saif Ullah Dar
 
Session no 2
Session no 2Session no 2
Session no 2
Saif Ullah Dar
 
C programming session 03
C programming session 03C programming session 03
C programming session 03
Dushmanta Nath
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
Saif Ullah Dar
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
Fahim Abdullah
 
Session 3 Java Script
Session 3 Java ScriptSession 3 Java Script
Session 3 Java Script
Muhammad Hesham
 
C language (Collected By Dushmanta)
C language  (Collected By Dushmanta)C language  (Collected By Dushmanta)
C language (Collected By Dushmanta)
Dushmanta Nath
 
Ad

Similar to C programming session 09 (20)

C programming session 13
C programming session 13C programming session 13
C programming session 13
Vivek Singh
 
Unit 4 qba
Unit 4 qbaUnit 4 qba
Unit 4 qba
Sowri Rajan
 
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
William Olivier
 
Structures
StructuresStructures
Structures
arshpreetkaur07
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
AjayBahoriya
 
C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
Emertxe Information Technologies Pvt Ltd
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Boro
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Kumar Boro
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
TawnaDelatorrejs
 
Chapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptxChapter 8 Structure Part 2 (1).pptx
Chapter 8 Structure Part 2 (1).pptx
Abhishekkumarsingh630054
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENT
Lori Moore
 
Lecture 3.mte 407
Lecture 3.mte 407Lecture 3.mte 407
Lecture 3.mte 407
rumanatasnim415
 
1 Goals. 1. To use a text file for output and later for in.docx
1 Goals. 1. To use a text file for output and later for in.docx1 Goals. 1. To use a text file for output and later for in.docx
1 Goals. 1. To use a text file for output and later for in.docx
honey690131
 
Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptx
ChereLemma2
 
Lesson 26 c programming ( union, storage classes)
Lesson 26 c programming ( union, storage classes)Lesson 26 c programming ( union, storage classes)
Lesson 26 c programming ( union, storage classes)
AparnaPriyadarsiniMe
 
Technical Interview
Technical InterviewTechnical Interview
Technical Interview
prashant patel
 
Fahri tugas cloud1
Fahri tugas cloud1Fahri tugas cloud1
Fahri tugas cloud1
FAHRIZAENURIPUTRA
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
Structure
StructureStructure
Structure
Renee Anne Cayabyab
 
PRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdfPRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdf
jaymaraltamera
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
Vivek Singh
 
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
William Olivier
 
C programming session 13
C programming session 13C programming session 13
C programming session 13
AjayBahoriya
 
Structures in c++
Structures in c++Structures in c++
Structures in c++
Swarup Boro
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
TawnaDelatorrejs
 
ADBMS ASSIGNMENT
ADBMS ASSIGNMENTADBMS ASSIGNMENT
ADBMS ASSIGNMENT
Lori Moore
 
1 Goals. 1. To use a text file for output and later for in.docx
1 Goals. 1. To use a text file for output and later for in.docx1 Goals. 1. To use a text file for output and later for in.docx
1 Goals. 1. To use a text file for output and later for in.docx
honey690131
 
Ch-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptxCh-3(b) - Variables and Data types in C++.pptx
Ch-3(b) - Variables and Data types in C++.pptx
ChereLemma2
 
Lesson 26 c programming ( union, storage classes)
Lesson 26 c programming ( union, storage classes)Lesson 26 c programming ( union, storage classes)
Lesson 26 c programming ( union, storage classes)
AparnaPriyadarsiniMe
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
michaelaaron25322
 
Ad

More from Dushmanta Nath (6)

Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
DBMS Practical File
DBMS Practical FileDBMS Practical File
DBMS Practical File
Dushmanta Nath
 
Manufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training ProjectManufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training Project
Dushmanta Nath
 
BSNL Training Project
BSNL Training ProjectBSNL Training Project
BSNL Training Project
Dushmanta Nath
 
IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)
Dushmanta Nath
 
IT-314 MIS (Practicals)
IT-314 MIS (Practicals)IT-314 MIS (Practicals)
IT-314 MIS (Practicals)
Dushmanta Nath
 
Global Warming Project
Global Warming ProjectGlobal Warming Project
Global Warming Project
Dushmanta Nath
 
Manufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training ProjectManufacturing Practice (MP) Training Project
Manufacturing Practice (MP) Training Project
Dushmanta Nath
 
IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)IT- 328 Web Administration (Practicals)
IT- 328 Web Administration (Practicals)
Dushmanta Nath
 
IT-314 MIS (Practicals)
IT-314 MIS (Practicals)IT-314 MIS (Practicals)
IT-314 MIS (Practicals)
Dushmanta Nath
 

Recently uploaded (20)

Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 

C programming session 09

  • 1. In this session, you will learn to: Work with structures Use structures in file handling Objectives
  • 2. 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. Working with Structures
  • 3. 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 . Defining Structures
  • 4. State whether True or False: The members of a structure must be of the same data type. 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. Practice: 7.1
  • 5. Solution: False 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. 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. 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: Memory is allocated for the structure ( date_type/ date ). Which of the following is/are the correct way(s) of referring to the variable day? a. day.date b. date_type.day Practice: 7.2
  • 8. What change(s) should be made to the first declaration so that the structure date is created of type date_type ? Is the following statement valid in case of the second declaration? If not, why? struct date another_date; Practice: 7.2 (Contd.)
  • 9. Solution: date (date_type is only a structure type) 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. 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  . Passing Structures to Functions
  • 11. Consider the following code: struct date_type { int day; int month; int year; }; struct date_type date, *ptr; How can the pointer variable ptr be assigned the address of the structure date ? 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. Practice: 7.3
  • 12. 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. Practice: 7.3 (Contd.)
  • 13. Solution: 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. 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]; Arrays of Structures
  • 15. 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. Practice: 7.4
  • 17. 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; }; Working with Structures (Contd.)
  • 18. What will the following declaration do? typedef char sentence[50]; sentence complex[10]; Practice: 7.5
  • 19. 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. 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. Using Structures in File Handling
  • 21. The fwrite() function is used to write structures onto a file. The f write() 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. Writing Records onto a File Using Structures
  • 22. 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. Practice: 7.6
  • 23. 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. Practice: 7.6 (Contd.)
  • 24. Solution: Practice: 7.6 (Contd.)
  • 25. 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. Reading Records from Files Using Structures
  • 26. 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. Practice: 7.7
  • 28. Debug the following program called dat.c using the error listing provided in the following file. Practice: 7.8
  • 29. Solution: The solution to this practice will be discussed in class. Work out your answer. Practice: 7.8 (Contd.)
  • 30. 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 Summary
  • 31. 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. Summary (Contd.)

Editor's Notes

  • #2: Begin the session by explaining the objectives of the session.
  • #3: Discuss the need for structures. Compare structure with an array.
  • #5: Use this slide to test the student’s understanding on defining structures.
  • #7: 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.
  • #8: Use this slide to test the student’s understanding on defining structures.
  • #11: Tell the students that structures can be passed to other functions. The structures can be passed either by value or by reference.
  • #12: Use this slide to test the student’s understanding on passing structures to functions.
  • #16: Use this slide to test the student’s understanding on array of structures.
  • #18: 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.
  • #19: Use this slide to test the student’s understanding on typedef statement.
  • #23: Use this slide to test the student’s understanding on the fwrite() function.
  • #26: 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 */ }
  • #27: Use this slide to test the student’s understanding on the fwrite() and fread() function.
  • #29: Use this slide to test the student’s understanding on reading and writing structures in a file.
  • #31: Use this and the next slide to summarize the session.