Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.

Similar presentations


Presentation on theme: "Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type."— Presentation transcript:

1 Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type

2 Prof. amr Goneid, AUC2 The Struct Data Type

3 Prof. amr Goneid, AUC3 The Struct Data Type What are Structs ? Definition & Declaration Accessing Members of a Struct Initializing a Struct Variable Compound Structs Structs as Operands & Arguments Pointers to Structs

4 Prof. amr Goneid, AUC4 1. What are structs? Structs are linear Data Structures. Unlike the array, components (members) can be of different types. string int longint int Member 1 Member 2 Member n One struct char

5 Prof. amr Goneid, AUC5 (a) Define a struct type: struct { ; …… ; }; (b) Declare variables of that type:.. ; 2. Definition & Declaration Required ;

6 Prof. amr Goneid, AUC6 Example // Definition of struct employee struct employee { string id; string name; char gender; int numDepend; money rate; money totWages; }; employee engineer, assistant;

7 Prof. amr Goneid, AUC7 3. Accessing Members of a struct Members are accessed using the member access operator, a period (.) For struct variable s and member variable m, to access m you would use: s.m Can use C++ operators and operations on struct members

8 Prof. amr Goneid, AUC8 Accessing Members of a struct engineer.id = “1234”; engineer.name = “Heba Ahmed”; engineer.gender = ‘F’; engineer.numDepend = 0; engineer.rate = 6.00; engineer.totWages += engineer.rate * 40.0;

9 Prof. amr Goneid, AUC9 What you can do with a whole struct Assign a struct to another struct with exactly the same structure (copy) Pass a struct to a function by value or by reference Return a struct as a function type

10 Prof. amr Goneid, AUC10 BUT you cannot Input or output a whole struct Do arithmetic with whole structs Compare two whole structs The above operations can only be done on individual members of structs

11 Prof. amr Goneid, AUC11 4. Initializing a Struct Variable Members can be initialized at the time a structure variable is created using a constructor A constructor is a special function that can be a member of a structure It is normally written inside the struct declaration Its purpose is to initialize the structure’s data members

12 Prof. amr Goneid, AUC12 Initializing using a Constructor Unlike most functions, a constructor is not called; instead, it is automatically invoked when a structure variable is created The constructor name must be the same as the structure Type name The constructor must have no return type

13 Prof. amr Goneid, AUC13 Initializing using a Constructor Example: struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H;} }; Usage: Dimensions box(12, 6, 3);

14 Prof. amr Goneid, AUC14 5. Compound structs: Structs with Array Members // Arrays can be fields of structs, e.g. struct studentRecord { string name; string id; floatgrade [10]; floatGPA; }; studentRecordstudent; student.grade[3] = 3.6; cin >> student.name; for( i = 0; i > student.grade[i];

15 Prof. amr Goneid, AUC15 Structs with Struct Members // A member of a struct may itself be a struct,e.g. struct nameType {cin >> person.address; string first;cin >> person.phone; string middle;cin >> person.name.first; string last;cin >> person.name.last; }; struct personInfo { nameType name; string address; string phone; }; personInfo person;

16 Prof. amr Goneid, AUC16 Structs with Struct Members struct point{ double x, y; }; point P; struct line{ point p1, p2; }; line L; struct triangle{ point p1, p2, p3; }; triangle T; p.x,p.y L.p1.x,L.p1.y L.p2.x,L.p2.y T.p1.x,T.p1.y T.p2.x,T.p2.y T.p3.x,T.p3.y

17 Prof. amr Goneid, AUC17 Arrays of Structs // A struct may be an element of an // array,e.g. personInfostaff [100]; cout << staff [i].address; cout << staff [i].name.first; for( i = 0; i < N; i++) { cout << staff [i].phone; cout << staff [i].name.family; }

18 Prof. amr Goneid, AUC18 6. Structs as Operands and Arguments Arithmetic and other operations can be done struct members Process entire struct using programmer defined functions Often better to pass an entire structure rather than individual elements struct copies: person = staff [6];

19 Prof. amr Goneid, AUC19 Passing struct as an Argument Grading program example Keep track of students grades Prior to our learning structs we needed to store each item into a single variable Group all related student items together Pass struct by const reference if you do not want changes made

20 Prof. amr Goneid, AUC20 Example(1): Grading Program // FILE: StudentStat.h struct studentStat { string name; int scores[3]; float average; char grade; };

21 Prof. amr Goneid, AUC21 PrintStats.cpp // File: printStats.cpp // Prints the exam statistics // Pre: The members of the struct variable // student are assigned values. // Post: Each member of student is displayed. void printStats(const studentStat student) { cout << "Exam scores for " << student. name << ": "

22 Prof. amr Goneid, AUC22 PrintStats.cpp cout << student.scores[0] << ' ' << student.scores[1]<< ' ' << student.scores[2] << endl; cout << "Average score: " << student.average << endl; cout << "Letter grade : " << student.grade << endl; }

23 Prof. amr Goneid, AUC23 Example(2): ReadEmp.cpp // File: ReadEmp.cpp // Reads one employee record into oneemployee #include // Pre: None // Post: Data are read into struct oneEmployee void readEmployee(employee& oneEmployee) { cout << "Enter a name terminated by # : ";

24 Prof. amr Goneid, AUC24 ReadEmp.cpp getline(cin, oneEmployee.name, '#'); cout << "Enter an id number: "; cin >> oneEmployee.id; cout << "Enter gender (F or M): "; cin >> oneEmployee.gender; cout << "Enter number of dependents: "; cin >> oneEmployee.numDepend; cout << "Enter hourly rate: "; cin >> oneEmployee.rate; }

25 Prof. amr Goneid, AUC25 7. Pointers to Structs struct electric { string current; int volts; }; electric*p,*q; //p and q are pointers to a struct of type electric

26 Prof. amr Goneid, AUC26 Pointers to Structs p = new electric; Allocates storage for struct of type electric and places address into pointer p Use operator (. ) to access struct members. ? currentvolts p ?

27 Prof. amr Goneid, AUC27 Assignments *p.current = “AC”; *p.volts = 220; Statements above can also be written as p ->current = “AC”; p ->volts = 220; AC currentvolts p 220

28 Prof. amr Goneid, AUC28 Struct Member Access via Pointers Form:p -> Example:p -> volts Example: cout current << p-volts << endl; Output AC220

29 Prof. amr Goneid, AUC29 Copy Dynamic Structs q = new electric; Allocates storage for struct of type electric and places address into pointer q Copy contents of p struct to q struct *q = *p; AC q ->currentq ->volts q 220

30 Prof. amr Goneid, AUC30 The Linked List Structure Structs and pointers can be used to arrange dynamically allocated structures into a new structure called a linked list Example: Consider a very long number represented as a string, e.g. π string Long_pi = “3.1415926535897932384626433832795028 8419716939937510……….”;

31 Prof. amr Goneid, AUC31 The Simple Linked List We can build a sequence of nodes linked by pointers: First node pointed to by head contains the first digit ‘3’and a next pointer to next node containing ‘.’ and so on. Last node’s next is NULL. A cursor points to the current node. It can advance in one way only to next node, e.g. to traverse whole list. 31 head NULL cursor. next First Last

32 Prof. amr Goneid, AUC32 The Node Structure struct node// specify node structure {char d;// digit or ‘.’ node *next;// pointer to next node }; node *head, *cursor, *p;// pointers to nodes d next

33 Prof. amr Goneid, AUC33 Code segment // Create first node p = new node; p->d = Long_pi[0]; p-> next = NULL; head = cursor = p; //Create rest of nodes for (i = 1; i < Long_pi.length(); i++){ p = new node; p->d = Long_pi[i]; p->next = NULL; cursor->next = p; cursor = cursor->next; }


Download ppt "Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type."

Similar presentations


Ads by Google