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

Slides:



Advertisements
Similar presentations
Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Operator Overloading Fundamentals
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
Starting Out with C++: Early Objects 5th Edition
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
More Arrays Arrays and classes Multi-dimensional Arrays Dynamic arrays.
 2006 Pearson Education, Inc. All rights reserved Pointers.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++
Basic Elements of C++ Chapter 2.
More Storage Structures A Data Type Defined by You Characteristics of a variable of a specific ‘data type’ has specific values or range of values that.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
1 Principles of Programming I Note Set #12. 2 Semester Overview Functions Character File I/O Arrays Pointers and Dynamic Memory Allocation Characters.
1 Chapter 16-1 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion.
1 Structures. Structure (struct) Definition A Structure is a container, it can hold a bunch of things. –These things can be of any type. Structures are.
1 STRUCTURES AND POINTERS. 2 A VARIABLE OF THIS COMPOSITE TYPE CAN HAVE MORE THAN ONE VALUE, GROUPED TOGETHER TO DESCRIBE AN ENTITY. THE COMPONENTS OF.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ Programming: Basic Elements of C++.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Lecture 26: Structures / struct s/. 2 Lecture Contents: t Basics of structs t Struct type definition ( struct reserved word) t Struct type definition.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data and Classes Chapter 7. Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together Structure.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
Chapter 7 A Data Types – Structures Structures Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Lecture 23: Pointers. 2 Lecture Contents: t Pointers and addresses t Pointers and function arguments t Pointers and arrays t Pointer arrays t Demo programs.
Review 1 List Data Structure List operations List Implementation Array Linked List.
Pointer Variables int i; declares an int variable and sets aside a named memory location to store the int int * iptr; declares a variable that holds the.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Struct Data Type in C++ What Are Structures?
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7. 12: Structures Starting Out with C++ Early Objects Eighth.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Prof. Amr Goneid, AUC1 CSCE 210 Data Structures and Algorithms Prof. Amr Goneid AUC Part R2. Elementary Data Structures.
CSCE 210 Data Structures and Algorithms
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7: Introduction to Classes and Objects
Basic Elements of C++.
CSCE 210 Data Structures and Algorithms
Linked lists.
CSCE 210 Data Structures and Algorithms
Data Types – Structures
Basic Elements of C++ Chapter 2.
Chapter 16-2 Linked Structures
Data Types – Structures
Struct Data Type in C++ What Are Structures?
Linked Lists Chapter 4.
Pointers & Dynamic Data Structures
Chapter 9: Pointers and String
Linked lists.
Programming Fundamental
Presentation transcript:

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

Prof. amr Goneid, AUC2 The Struct Data Type

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

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

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

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;

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

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;

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

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

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

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

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

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];

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;

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

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; }

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];

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

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

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 << ": "

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; }

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 # : ";

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; }

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

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 ?

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

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

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

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 = “ ……….”;

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

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

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; }