Download presentation
1
C Programming Structured Data
2
Combining Data into Structures
Structure: C construct that allows multiple variables to be grouped together Structure Declaration Format: struct structure name { type1 field1; type2 field2; … typen fieldn; };
3
Example struct Declaration
struct Student { int studentID; string name; short year; double gpa; }; structure tag structure members Notice the required ;
4
struct examples Example: The “StudentGrade” structure has 5 members of
struct StudentInfo{ int Id; int age; char Gender; double CGA; }; struct StudentGrade{ char Name[15]; char Course[9]; int Lab[5]; int Homework[3]; int Exam[2]; The “StudentInfo” structure has 4 members of different types. The “StudentGrade” structure has 5 members of different array types.
5
struct examples Example: The “StudentRecord” structure has 4
struct BankAccount{ char Name[15]; int AcountNo[10]; double balance; Date Birthday; }; struct StudentRecord{ int Id; char Dept[5]; char Gender; The “BankAcount” structure has simple, array and structure types as members. The “StudentRecord” structure has 4 members.
6
struct Declaration Notes
struct names commonly begin with an uppercase letter Multiple fields of same type can be in a comma-separated list string name, address;
7
Defining Structure Variables
struct declaration does not allocate memory or create variables To define variables, use structure tag as type name Student s1; studentID name year gpa s1
8
Example: structures struct date
{ int month; int day; int year; }; Defines type struct date, with 3 fields of type int The names of the fields are local in the context of the structure. A struct declaration defines a type: if not followed by a list of variables it reserves no storage; it merely describes a template or shape of a structure. Defines 3 variables of type struct date struct date today, purchaseDate; today.year = 2004; today.month = 10; today.day = 5; Accesses fields of a variable of type struct date A member of a particular structure is referred to in an expression by a construction of the form structurename.member
10
Structure definition To define a structure for student’s information
typedef struct { char [30] name; int age; } student; Student s1, s2;
11
Structure using When we use the structure data as S1.age = 21;
Strcpy(s1.name, “mohamed”); Strcpy(s2.name, “ahmed”);
12
Accessing Structure Members
Use the dot (.) operator to refer to members of struct variables Printf(“%d”, s1.studentID); s1.gpa = 3.75; Member variables can be used in any manner appropriate for their data type
13
Displaying struct Members
To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s1; // won’t work! Correct: cout << s1.studentID << endl; cout << s1.name << endl; cout << s1.year << endl; cout << s1.gpa; See pr7-01.cpp and pr7-02.cpp
14
Initializing a Structure
Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int studentID = 1145; string name = "Alex"; short year = 1; float gpa = 2.95; };
15
Example Write a program which accepts from the user via the keyboards, and the following data items: it_number – integer value, name – string, up to 20 characters, amount – integer value. Your program will store this data for 3 persons and display each record is proceeded by the record number.
16
Comparing struct Variables
Cannot compare struct variables directly: if (stu1 == stu2) // won’t work Instead, must compare on a member basis: if (stu1.studentID == stu2.studentID)
17
Initializing a Structure (continued)
Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either an initialization list a constructor
18
Using an Initialization List
An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list // with 3 values
19
More on Initialization Lists
Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list // with 3 items
20
Initialization List Example
Structure Declaration Structure Variable struct Dimensions { int length, width, height; }; Dimensions box = {12,6,3}; box length 12 width 6 height 3
21
Partial Initialization
Can initialize just some members, but cannot skip over members Dimensions box1 = {12,6}; //OK Dimensions box2 = {12,,3}; //illegal
22
Problems with Initialization List
Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects Will, however, work with C-string members
23
Omit () when no arguments are used
Examples //Create a box with all dimensions given Dimensions box4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box5(12, 6); //Create a box using all default values Dimensions box6; See pr7-03.cpp Omit () when no arguments are used
24
Example Write a car struct that has the following fields: YearModel (int), Make (string), and Speed (int). The program has function assign_data ( ) accelerate ( ) which add 5 to the speed each time it is called, break () which subtract 5 from speed each time it is called, and display () to print out the car’s information.
25
Nested Structures A structure can have another structure as a member.
struct PersonInfo { string name, address, city; }; struct Student { int studentID; PersonInfo pData; short year; double gpa;
26
Members of Nested Structures
Use the dot operator multiple times to dereference fields of nested structures Student s5; s5.pData.name = "Joanne"; s5.pData.city = "Tulsa"; See pr7-04.cpp
27
Example Create a structTime that contains data members, hour, minute, second to store the time value, provide a function that sets hour, minute, second to zero, provide three function for converting time to ( 24 hour ) and another one for converting time to ( 12 hour ) and a function that sets the time to a certain value specified by three parameters
28
Arrays of Structures Structures can be defined in arrays
Structures can be used in place of parallel arrays Student stuList[20]; Individual structures accessible using subscript notation Fields within structures accessible using dot notation: cout << stuList[5].studentID;
29
Structures as Function Arguments
May pass members of struct variables to functions computeGPA(s1.gpa); May pass entire struct variables to functions showData(s5); Can use reference parameter if function needs to modify contents of structure variable
30
Example Coffee shop needs a program to computerize its inventory. The data will be Coffee name, price, and amount in stock, sell by year. The function on coffee are: prepare to enter stock, Display coffee data, change price, add stock (add new batch), sell coffee, remove old stock (check sell by year).
31
Notes on Passing Structures
Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void showData(const Student &s) // header See pr7-05.cpp
32
Returning a Structure from a Function
Function can return a struct Student getStuData(); // prototype s1 = getStuData(); // call Function must define a local structure for internal use to use with return statement
33
Returning a Structure Example
Student getStuData() { Student s; // local variable cin >> s.studentID; cin.ignore(); getline(cin, s.pData.name); getline(cin, s.pData.address); getline(cin, s.pData.city); cin >> s.year; cin >> s.gpa; return s; } See pr7-06.cpp
34
Example Design a struct named BankAccount with data: balance, number of deposits this month, number of withdrawals, annual interest rate, and monthly service charges. The program has functions: Deposit (amount) {add amount to balance and increment number of deposit by one}, Withdraw (amount) {subtract amount from balance and increment number of withdrawals by one}, CalcInterest() { update balance by amount = balance * (annual interest rate /12)}, and MonthlyPocess() {subtract the monthly service charge from balance, set number of deposit, number of withdrawals and monthly service charges to zero}.
35
Pointers to Structures
A structure variable has an address Pointers to structures are variables that can hold the address of a structure: Student * stuPtr, stu1; Use the & operator to assign an address: stuPtr = & stu1; A structure pointer can be a function parameter
36
Accessing Structure Members via Pointer Variables
Use () to dereference the pointer variable, not the field within the structure: cout << (*stuPtr).studentID; You can use the structure pointer operator ( -> ), a.k.a arrow operator to eliminate use of(*). cout << stuPtr -> studentID;
37
Pointers to Structures
You may take the address of a structure variable and create variables that are pointers to structures. Circle *cirPtr; // cirPtr is a pointer to a Circle CirPtr = &piePlate; *cirPtr.radius = 10; // incorrect way to access Radius because the dot operator // has higher precedence than the indirection operator (*cirPtr).radius = 10; //correct access to Radius cirPtr -> radius = 10; // structure pointer operator ( -> ), easier notation for // dereferencing structure pointers
38
Example Write a complete program to
Define a person struct with members: ID, name, address, and telephone number. The functions are change_data( ), get_data( ), and display_data( ). Declare record table with size N and provide the user to fill the table with data. Allow the user to enter certain ID for the Main function to display the corresponding person's name, address, and telephone number.
39
Linked List
40
Unions Similar to a struct, but Declared using key word union
all members share a single memory location (which saves space) only 1 member of the union can be used at a time Declared using key word union Otherwise the same as struct Variables defined and accessed like struct variables
41
Example union Declaration
union WageInfo { double hourlyRate; float annualSalary; }; union tag union members See pr7-07.cpp Notice the required ;
42
Anonymous Union A union without a tag:
With no tag you cannot create additional union variables of this type later Allocates memory at declaration time Refer to members directly without dot operator See pr7-08.cpp
43
Enumerated Data Types An enumerated data type is a programmer-defined data type. It consists of values known as enumerators, which represent integer constants.
44
Enumerated Data Types Example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; The identifiers MONDAY, TUESDAY, WEDNESDAY, THURSDAY, and FRIDAY, which are listed inside the braces, are enumerators. They represent the values that belong to the Day data type. The enumerators are named constants.
45
Enumerated Data Types Once you have created an enumerated data type in your program, you can define variables of that type. Example: Day workDay; This statement defines workDay as a variable of the Day type.
46
Enumerated Data Types We may assign any of the enumerators MONDAY, TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type. Example: workDay = WEDNESDAY;
47
Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; In memory... MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4
48
Enumerated Data Types Using the Day declaration, the following code...
cout << MONDAY << " " << WEDNESDAY << " “ << FRIDAY << endl; ...will produce this output:
49
Assigning an Enumerator to an int Variable
You CAN assign an enumerator to an int variable. For example: int x; x = THURSDAY; This code assigns 3 to x.
50
Enumerated Data Types Program shows enumerators used to control a loop: // Get the sales for each day. for (index = MONDAY; index <= FRIDAY; index++) { cout << "Enter the sales for day " << index << ": "; cin >> sales[index]; } // Would not work if index was an enumerated type
51
Using an enum Variable to Step through an Array's Elements
Because enumerators are stored in memory as integers, you can use them as array subscripts. For example: enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; const int NUM_DAYS = 5; double sales[NUM_DAYS]; sales[MONDAY] = ; sales[TUESDAY] = ; sales[WEDNESDAY] = ; sales[THURSDAY] = ; sales[FRIDAY] = ;
52
STRUCT, TYPEDEF, ENUM & UNION
You cannot use the typedef specifier inside a function definition. When declaring a local-scope identifier by the same name as a typedef, or when declaring a member of a structure or union in the same scope or in an inner scope, the type specifier must be specified. For example, typedef float TestType; int main(void) { ... } // function scope (local) int MyFunct(int) { // same name with typedef, it is OK int TestType; } ©
53
STRUCT, TYPEDEF, ENUM & UNION
Names for structure types are often defined with typedef to create shorter and simpler type name. For example, the following statements, typedef struct Card MyCard; typedef unsigned short USHORT; Defines the new type name MyCard as a synonym for type struct Card and USHORT as a synonym for type unsigned short. Programmers usually use typedef to define a structure (also union, enum and class) type so a structure tag is not required. For example, the following definition. typedef struct{ char *face; char *suit; } MyCard;
54
Creating Header File and File Re-inclusion Issue
It is a normal practice to separate structure, function, constants, macros, types and similar definitions and declarations in a separate header file(s). Then, those definitions can be included in main() using the include directive (#include). It is for reusability and packaging and to be shared between several source files. Include files are also useful for incorporating declarations of external variables and complex data types. You need to define and name the types only once in an include file created for that purpose. The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. ©
55
The syntax is one of the following,
#include "path-spec" #include <path-spec> Both syntax forms cause replacement of that directive by the entire contents of the specified include file. The difference between the two forms is the order in which the preprocessor searches for header files when the path is incompletely specified. Preprocessor searches for header files when the path is incompletely specified. ©
56
Bitwise Operators All data is represented internally as sequences of bits Each bit can be either 0 or 1 Sequence of 8 bits forms a byte
57
Exercise: even or odd testing if an integer is even or odd, using bitwise operations: the rightmost bit of any odd integer is 1 and of any even integer is 0. int n; if ( n & 1 ) printf(“odd”); else printf(“even”);
58
Fig. 10.6 | Bitwise operators.
59
Fig. 10.8 | Results of combining two bits with the bitwise AND operator &.
60
Fig. 10.11 | Results of combining two bits with the bitwise inclusive OR operator |.
61
Fig. 10.12 | Results of combining two bits with the bitwise exclusive OR operator ^.
62
Outline fig10_10.c
63
Outline fig10_13.c (1 of 3 ) Left shift operator shifts all bits left a specified number of spaces, filling in zeros for the empty bits
64
Outline fig10_13.c (2 of 3 ) Right shift operator shifts all bits right a specified number of spaces, filling in the empty bits in an implementation-defined manner
65
Outline fig10_13.c (3 of 3 )
66
Fig. 10.14 | The bitwise assignment operators.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.