Problem Solving and Program Design in C Chap. 11 Structure and Union Types Chow-Sing Lin.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Structure and Union Types Problem Solving & Program Design.
Intermediate Code Generation
C Structures and Memory Allocation There is no class in C, but we may still want non- homogenous structures –So, we use the struct construct struct for.
Programming and Data Structure
Structures Spring 2013Programming and Data Structure1.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Structure and Union Types Problem Solving & Program Design.
Chapter 11 Structure and Union Types Instructor: Alkar / Demirer.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
The scanf Function The scanf function reads input from the standard input device into one or more variables Example: scanf(“%lf”, &miles); Reads a real.
Basic C Programming Data Types and Arithmetic Operations 01/30/15.
CS 201 Structure & Union Debzani Deb.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 11 Structure and Union Types Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
User-defined Structure Types Structures: collection of data of different types. We can define a structure type student_t : typedef struct { string name;
Data types and variables
Structure and Union Types 程式設計 潘仁義 CCU COMM. Structure Type Definition struct structured data objects, can be defined by users #define STRSIZ 10 typedef.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
TDBA66, Lecture Ch. 11, vt-03 1 Abstraction Prucedural abstraction moduralize by hiding the details in a function() Ex.functions in get_params(…) display_match(…)
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Introduction to C Programming
Chapter 15: Operator Overloading
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Objectives You should be able to describe: Data Types
Data Structures Using C++ 2E Chapter 3 Pointers and Array-Based Lists.
S-1 University of Washington Computer Programming I Lecture 18: Structures © 2000 UW CSE.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
Data Structures Using C++ 2E Chapter 3 Pointers. Data Structures Using C++ 2E2 Objectives Learn about the pointer data type and pointer variables Explore.
Pointers: Basics. 2 What is a pointer? First of all, it is a variable, just like other variables you studied  So it has type, storage etc. Difference:
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Chapter 11 Structure and Union Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
+ Structures and Unions. + Introduction We have seen that arrays can be used to represent a group of data items that belong to the same type, such as.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
PHP Programming with MySQL Slide 3-1 CHAPTER 3 Working with Data Types and Operators.
Operators & Expressions
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
CISC105 – General Computer Science Class 2 – 6/7/2006.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Gator Engineering Project 1 Grades released Re-grading –Within one week –TA: Fardad, or office hours: MW 2:00 – 4:00 PM TA Huiyuan’s office hour.
chap11 Chapter 11 Structure and Union Types.
Problem Solving and Program Design in C Chap. 6 Pointers and Modular Programming Chow-Sing Lin.
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Pointers: Basics. 2 Address vs. Value Each memory cell has an address associated with it
© 2012 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Programming application CC213 Week 08 – Struct & Unions– Chapter 10.
Introduction We will study how to broaden the modeling facilities of C by defining our own data types that represent structured collections of data pertaining.
Introduction to C++ Programming
Structure and Union Types
C Operators, Operands, Expressions & Statements
Structure and Union Types
READING AND PRINTING MATRICES (with functions)
Chapter 10 C Structures and Unions
Chapter 11 Structure and Union Types.
Presentation transcript:

Problem Solving and Program Design in C Chap. 11 Structure and Union Types Chow-Sing Lin

User-Defined Structure Types Define our own data types that represent structured collections of data pertaining to particular objects. Unlike array, a structure can have individual components that contain data of different types. Each of data items is stored in a separate component of the structure and can be referenced by using the component name. Database – A collection of information stored in a computer’s memory or in a disk – A database is subdivided into records, which normally contain information regarding specific data objects – The structure of the record is determined by the structure of the object’s data type Dr. Chow-Sing LinStructure and Union Types - CH112

Structure Type Definition Before a structured data object can be created or saved, the format of its components must be defined Defining a new data type for each category of structured objects Dr. Chow-Sing LinStructure and Union Types - CH113

Structure Type Definition (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH114 typedef struct { type 1 id_list 1 ; type 2 id_list 2 ; type n id_list n ; } struct_type; SYNTAX typedef struct { /* complex number structure */ double real_pt, imag_pt; } complex_t ; Example

Example 10.1 Develop a database of the planets in our solar system – We need to represent information Name: Jupiter Diameter: 142,800 km Moons: 16 Orbit: 11.9 yr Rotation time: hr Dr. Chow-Sing LinStructure and Union Types - CH115

Example 11.1 (Cont.) The structure type planet_t has five distinct components – Array of characters (string) – int – The other three are of type double Dr. Chow-Sing LinStructure and Union Types - CH116 #define STRSIZ 10 typedef struct { char name[STRSIZ]; double diameter; /* equatorial diameter in km */ int moons;/* number of moons*/ double orbit_time, /* years to orbit sun once*/ rotataion_time;/* hours to complete one revolution on axis*/ } planet_t;

Example 11.1 (Cont.) { planet_t current_planet, previous_plant, blank_plant = {“ ”,0,0,0,0}; ………. } Dr. Chow-Sing LinStructure and Union Types - CH117

Example 11.1 (Cont.) The variable blank_planet is pictured as it appears after initialization Dr. Chow-Sing LinStructure and Union Types - CH118 Variable blank_planet, a structure of type planet_t.name\0 ? ? ? ? ? ? ? ? ?.diameter0.0.moons 0.orbit_time0.0.rotation_time0.0

Example 10.1 (Cont.) Hierarchical structure – A structure containing component that are data structures (array or structs) Dr. Chow-Sing LinStructure and Union Types - CH119 typedef struct { double diameter; planet_tplanets[9]; chargalaxy[STRSIZ]; } solar_sys_t ;

Manipulating Individual Components of a Structured Data Object Direct component selection operator – A period placed between a structure type variable and a component name to create a reference to the component Dr. Chow-Sing LinStructure and Union Types - CH1110

Example 10.2 Assigning Values to Components of Variable current_planet Dr. Chow-Sing LinStructure and Union Types - CH1111

Example 11.2 (Cont.) Once data are stored in a record – Can be manipulated in the same way as other data in memory Dr. Chow-Sing LinStructure and Union Types - CH1112 printf (“%s’s equatorial diameter is %.1f km. \n”, current_planet.name, current_planet.diameter ); Jupiter’s equatorial diameter is km. display

Review of Operator Precedence In a generic expression containing two of the same operators in sequence – operand 1 op operand 2 op operand 3 If op has left associatively (operand 1 op operand 2 ) op operand 3 If op has right associatively operand 1 op (operand 2 op operand 3 ) Dr. Chow-Sing LinStructure and Union Types - CH1113

Dr. Chow-Sing LinStructure and Union Types - CH1114 PrecedenceSymbolOperator NamesAssociatively a [ j ] f(…). Subscripting, function calls, direct component selection left Postfix increment and decrement left ! Prefix increment and decrement right - + & * logical not, unary negation and plus, address of, indirection (type name) Casts right * / % Multiplicative operators (multiplication, division, remainder) left + - Binary additive operators (addition and subtraction) left = Relational operators left == != Equality/inequality operators left && Logical and left || Logical or left = += -= *= /= %= Assignment operators right highest lowest

Manipulating Whole Structures The name of a structure type variable used with no component selection operator refers to the entire structure Make a new copy of a structure’s value Dr. Chow-Sing LinStructure and Union Types - CH1115 previous_planet = current_planet;

Structure type data as input and output parameters When a structured variable is passed as an input argument to a function, all of its component values are copied into the components of the function’s corresponding formal parameter When such a variable is used as an output argument, the address-of operator must be applied Dr. Chow-Sing LinStructure and Union Types - CH1116

Example 10.3 To display the value of structure current_planet print_planet(current_planet); Dr. Chow-Sing LinStructure and Union Types - CH1117

Structure type data as input and output parameters (Cont.) Function Comparing two structured values for equality – Returns 1 or 0 depending on whether all components match Dr. Chow-Sing LinStructure and Union Types - CH1118

Structure type data as input and output parameters (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1119 Return the value 1 if its single output argument is successfully filled Return the value 0 if there is an error Return the negative value EOF if the end of the file is encountered

Structure type data as input and output parameters (Cont.) Manipulating a structured output argument using operators “*” and “.” requires to keep operator-precedence rules (Table 10.1). – Direct component selection (.) has the highest precedence (LEFT) – &*plnp.diameter? Or &(*plnp).diameter? Dr. Chow-Sing LinStructure and Union Types - CH1120

Structure type data as input and output parameters (Cont.) In order to use scanf to store a value in one component of the structure whose address is in plnp – steps(in order) Follow the pointer in plnp to the structure Select the component of interest Unless this component is an array get its address to pass to scanf &*plnp.diameter  &(*plnp).diameter Dr. Chow-Sing LinStructure and Union Types - CH1121

Structure type data as input and output parameters (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1122

Analysis of Reference &(*plnp).diameter Dr. Chow-Sing LinStructure and Union Types - CH1123 ReferenceTypeValue plnpplanet_t *address of structure that main refers to as current_planet *plnpplanet_tstructure that main refers to as current_planet (*plnp).diameterdouble &(*plnp).diameterdouble *Address of colored component of structure that main refers to as current_planet

Indirect component selection operator – “->” a minus sign followed by a greater-than symbol follows the pointer to a structure and selects the component (*structp).component == structp->component Dr. Chow-Sing LinStructure and Union Types - CH1124

Indirect component selection operator (Cont.) If we rewrite the scan_planet function of – Fig.10.4 using the “->” operator – the assignment to result will be Dr. Chow-Sing LinStructure and Union Types - CH1125 result = scanf (“%s%lf%d%lf%lf”, plnp->name, &plnp->diameter, &plnp->moons, &plnp->orbit_time, &plnp->rotation_time);

Functions whose result values are structured A function that computes a structured result can be modeled on a function computing a simple result A local variable of the structure type can be allocated, filled with the desired data, and returned as the function result The function does not return the address of the structure as it would with an array; rather is returns the values of all components Dr. Chow-Sing LinStructure and Union Types - CH1126

Functions whose result values are structured (Cont.) Dr. Chow-Sing LinStructure and Union Types - CH1127

Functions whose result values are structured (Cont.) Like function getchar, our function get_planet requires no arguments. If we assume entry of correct data, statement current_planet = get_planet(); has the same effect as scan_planet(&current_planet); Example 10.5 Dr. Chow-Sing LinStructure and Union Types - CH1128

Problem Solving with Structure Types Abstract data type(ADT) – Combining a user-defined type with a set of basic operations – No longer bogged down in the details of manipulating the type’s components Dr. Chow-Sing LinStructure and Union Types - CH1129

Case Study A User-Defined Type for Complex Numbers – Develop a user-defined structure type and a set of operations – Make complex-arithmetic virtually as straightforward as arithmetic on C’s built-in numeric types Read Book Page 604~605 Code Page 606~611 Dr. Chow-Sing LinStructure and Union Types - CH1130

Dr. Chow-Sing LinStructure and Union Types - CH1131

Dr. Chow-Sing LinStructure and Union Types - CH1132

Dr. Chow-Sing LinStructure and Union Types - CH1133

Dr. Chow-Sing LinStructure and Union Types - CH1134

Dr. Chow-Sing LinStructure and Union Types - CH1135

Parallel Arrays and Arrays of Structures A data collection contains items of different types or items that, although of the same type, represent quite distinct concepts – For example The data used to represent a list of students might consist of – an integer identification number – a type double gpa for each student A polygon might be a list of the(x,y) coordinates of the polygon’s corners. Dr. Chow-Sing LinStructure and Union Types - CH1136

Parallel Arrays Array id and gpa are called parallel arrays int id[50]; /* id number and double gpa[50]; /* gpa’s of up to 50 students */ The ith elements of arrays x and y are the coordinates of one point double x[NUM_PTS], /* (x,y) coordinates of*/ double y[NUM_PTS]; /* up to NUM_PTS points*/ Dr. Chow-Sing LinStructure and Union Types - CH1137

Declaring an Array of Structures Group the information in a structure whose type we define Dr. Chow-Sing LinStructure and Union Types - CH1138 #define MAX_STU 50 #define NUM_PTS 10 typedef struct { int id; double gpa; } student_t; typedef struct { double x,y; } point_t; … { student_t stulist[MAX_STU]; point_t polygon[NUM_PTS];

Declaring an Array of Structures (cont.) Function scan_student is available for scanning a student_t structure – for statement can be used to fill the entire array stulist with data Dr. Chow-Sing LinStructure and Union Types - CH1139 for (i=0; i < MAX_STU; ++i) scan_student(&stulist[i]);

Case Study Universal Measurement Conversion – Spell-checks text and looks up synonyms for words – the conversion request 450 km miles – program output Attempting conversion of km to miles … km = miles Read Book Page 614~616 Code Page 617~622 Dr. Chow-Sing LinStructure and Union Types - CH1140

Dr. Chow-Sing LinStructure and Union Types - CH1141

Dr. Chow-Sing LinStructure and Union Types - CH1142

Dr. Chow-Sing LinStructure and Union Types - CH1143

Dr. Chow-Sing LinStructure and Union Types - CH1144

Dr. Chow-Sing LinStructure and Union Types - CH1145

Dr. Chow-Sing LinStructure and Union Types - CH1146

Union Types (Optional) So far, all variables we have seen of a particular structure type have had exactly the same components. Sometimes we need structured types in which some components vary depending on the value of another component. Union – a data structure that overlays components in memory – allowing one data object (a chunk of memory) to be interpreted in multiple ways Dr. Chow-Sing LinStructure and Union Types - CH1147

Example 10.6 define a union structure – use as the type of one component of a person’s physical description If the person has hair – record the hair color If the person is bald – note whether or not this baldness is disguised by a wig Dr. Chow-Sing LinStructure and Union Types - CH1148

Example 10.6 (Cont.) typedef statement allocates no memory declaration hair_t hair_data; – Creates a variable hair_data built on the template of the type definition – The variable hair_data has either a wears_wig component or a color component Dr. Chow-Sing LinStructure and Union Types - CH1149 typedef union { int wears_wig; char color[20]; } hair_t;

Example 10.6 (Cont.) When memory is allocated for hair_data – the amount of memory is determined by the largest component of the union a structure containing a hair_t union componet Dr. Chow-Sing LinStructure and Union Types - CH1150 typedef struct { int bald; hair_t h; } hair_info_t wears_wig color

Example 10.6 (Cont.) Function That Displays a Structure with a Union Type Component Dr. Chow-Sing LinStructure and Union Types - CH1151

Example 10.6 (Cont.) Two Interpretations of Parameter hair Dr. Chow-Sing LinStructure and Union Types - CH1152

Example 10.7 Hierarchical structure definition Dr. Chow-Sing LinStructure and Union Types - CH1153

1-54 Figure Program to Compute Area and Perimeter of Geometric Figures

1-55 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)

1-56 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)

1-57 Figure Program to Compute Area and Perimeter of Geometric Figures (cont’d)