C Programming Structured Data Combining Data into Structures

C Programming Structured Data

Combining Data into Structures • Structure: C construct that allows multiple variables to be grouped together • Structure Declaration Format: structure name { type 1 field 1; type 2 field 2; … typen fieldn; };

Example struct Declaration struct Student { int student. ID; string name; short year; double gpa; }; structure tag structure members Notice the required ;

struct examples • Example: struct Student. Info{ int Id; int age; char Gender; double CGA; }; The “Student. Info” structure has 4 members of different types. • Example: struct Student. Grade{ char Name[15]; char Course[9]; int Lab[5]; int Homework[3]; int Exam[2]; }; The “Student. Grade” structure has 5 members of different array types. 4
![struct examples • Example: struct Bank. Account{ char Name[15]; int Acount. No[10]; double balance; struct examples • Example: struct Bank. Account{ char Name[15]; int Acount. No[10]; double balance;](http://slidetodoc.com/presentation_image_h2/71a79460d133e8ecfb799e3c73ae3fbf/image-5.jpg)
struct examples • Example: struct Bank. Account{ char Name[15]; int Acount. No[10]; double balance; Date Birthday; }; The “Bank. Acount” structure has simple, array and structure types as members. • Example: struct Student. Record{ char Name[15]; int Id; char Dept[5]; char Gender; }; The “Student. Record” structure has 4 members. 5

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;

Defining Structure Variables • struct declaration does not allocate memory or create variables • To define variables, use structure tag as type name s 1 Student s 1; student. ID name year gpa

Example: structures struct date Defines type struct date, with 3 fields of type int { The names of the fields are local in the context of the structure. int month; int day; int year; }; 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. struct date today, purchase. Date; today. year = 2004; today. month = 10; today. day = 5; Defines 3 variables of type struct date 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

9

Structure definition • To define a structure for student’s information typedef struct { char [30] name; int age; } student; Student s 1, s 2;

Structure using • When we use the structure data as S 1. age = 21; S 2. age = 20; Strcpy(s 1. name, “mohamed”); Strcpy(s 2. name, “ahmed”);

Accessing Structure Members • Use the dot (. ) operator to refer to members of struct variables Printf(“%d”, s 1. student. ID); s 1. gpa = 3. 75; • Member variables can be used in any manner appropriate for their data type

Displaying struct Members • To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s 1; // won’t work! Correct: cout << << s 1. student. ID << endl; s 1. name << endl; s 1. year << endl; s 1. gpa;

Initializing a Structure • Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int student. ID = 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.

Comparing struct Variables • Cannot compare struct variables directly: if (stu 1 == stu 2) // won’t work • Instead, must compare on a member basis: if (stu 1. student. ID == stu 2. student. ID)

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

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

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

Initialization List Example Structure Declaration struct Dimensions { int length, width, height; }; Structure Variable box length 12 width 6 3 height Dimensions box = {12, 6, 3};

Partial Initialization • Can initialize just some members, but cannot skip over members Dimensions box 1 = {12, 6}; //OK Dimensions box 2 = {12, , 3}; //illegal

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

Examples //Create a box with all dimensions given Dimensions box 4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box 5(12, 6); //Create a box using all default values Dimensions box 6; Omit () when no arguments are used

Example • Write a car struct that has the following fields: Year. Model (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.

Nested Structures A structure can have another structure as a member. struct Person. Info { string name, address, city; }; struct Student { int student. ID; Person. Info p. Data; short year; double gpa; };

Members of Nested Structures • Use the dot operator multiple times to dereference fields of nested structures Student s 5; s 5. p. Data. name = "Joanne"; s 5. p. Data. city = "Tulsa";

Example • Create a struct. Time 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

Arrays of Structures • Structures can be defined in arrays • Structures can be used in place of parallel arrays Student stu. List[20]; • Individual structures accessible using subscript notation • Fields within structures accessible using dot notation: cout << stu. List[5]. student. ID;

Structures as Function Arguments • May pass members of struct variables to functions compute. GPA(s 1. gpa); • May pass entire struct variables to functions show. Data(s 5); • Can use reference parameter if function needs to modify contents of structure variable

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).

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 show. Data(const Student &s) // header

Returning a Structure from a Function • Function can return a struct Student get. Stu. Data(); s 1 = get. Stu. Data(); // prototype // call • Function must define a local structure – for internal use – to use with return statement

Returning a Structure Example Student get. Stu. Data() { Student s; // local variable cin >> s. student. ID; cin. ignore(); getline(cin, s. p. Data. name); getline(cin, s. p. Data. address); getline(cin, s. p. Data. city); cin >> s. year; cin >> s. gpa; return s; }

Example • Design a struct named Bank. Account 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}, Calc. Interest() { update balance by amount = balance * (annual interest rate /12)}, and Monthly. Pocess() {subtract the monthly service charge from balance, set number of deposit, number of withdrawals and monthly service charges to zero}.

Pointers to Structures • A structure variable has an address • Pointers to structures are variables that can hold the address of a structure: Student * stu. Ptr, stu 1; • Use the & operator to assign an address: stu. Ptr = & stu 1; • A structure pointer can be a function parameter

Accessing Structure Members via Pointer Variables • Use () to dereference the pointer variable, not the field within the structure: cout << (*stu. Ptr). student. ID; • You can use the structure pointer operator ( -> ), a. k. a arrow operator to eliminate use of(*). cout << stu. Ptr -> student. ID;

Pointers to Structures • You may take the address of a structure variable and create variables that are pointers to structures. Circle *cir. Ptr; Cir. Ptr = &pie. Plate; // cir. Ptr is a pointer to a Circle *cir. Ptr. radius = 10; // incorrect way to access Radius because the dot operator // has higher precedence than the indirection operator (*cir. Ptr). radius = 10; //correct access to Radius cir. Ptr -> radius = 10; // structure pointer operator ( -> ), easier notation for // dereferencing structure pointers

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

Linked List

Unions • Similar to a struct, but – 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

Example union Declaration union Wage. Info { double hourly. Rate; float annual. Salary; }; union tag union members Notice the required ;

Anonymous Union • A union without a tag: union {. . . }; • 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

Enumerated Data Types • An enumerated data type is a programmerdefined data type. It consists of values known as enumerators, which represent integer constants.

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.

Enumerated Data Types • Once you have created an enumerated data type in your program, you can define variables of that type. Example: Day work. Day; • This statement defines work. Day as a variable of the Day type.

Enumerated Data Types • We may assign any of the enumerators MONDAY, TUESDAY, WEDNESDAY, THURSDAY, or FRIDAY to a variable of the Day type. • Example: work. Day = WEDNESDAY;

Enumerated Data Types enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }; In memory. . . MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4

Enumerated Data Types • Using the Day declaration, the following code. . . cout << MONDAY << " " << WEDNESDAY << " “ << FRIDAY << endl; . . . will produce this output: 0 2 4

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.

Enumerated Data Types • Program shows enumerators used to control a loop: // Get the sales for each day. for (index { cout << << cin >> } = MONDAY; index <= FRIDAY; index++) "Enter the sales for day " index << ": "; sales[index]; // Would not work if index was an enumerated type

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] = = = 1525. 00; 1896. 50; 1975. 63; 1678. 33; 1498. 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 Test. Type; int main(void) {. . . } // function scope (local) int My. Funct(int) { // same name with typedef, it is OK int Test. Type; } www. tenouk. com, © 57/93

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 My. Card; typedef unsigned short USHORT; § § § Defines the new type name My. Card 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; } My. Card; 62/93

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. www. tenouk. com, © 54/93

§ The syntax is one of the following, 1. #include 2. #include "path-spec" <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. www. tenouk. com, © 42/93

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

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 fig 10_10. c

63 Outline fig 10_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 fig 10_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 fig 10_13. c (3 of 3 )

66 Fig. 10. 14 | The bitwise assignment operators.
- Slides: 66