 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Copyright © 2002 Pearson Education, Inc. Slide 1.
1 Programming Structures COMP102 Prog. Fundamentals, Structures / Slide 2 2 Structures l A Structure is a collection of related data items, possibly.
Structure.
C++ Basics March 10th. A C++ program //if necessary include headers //#include void main() { //variable declaration //read values input from user //computation.
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Monday, 11/11/02, Slide #1 CS 106 Intro to Comp. Sci. 1 Monday, 11/11/02  Questions? HW 04 due today at 5.  Today – Lists and an introduction to searching.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Overview 10.1 Structures 10.2 Classes 10.3 Abstract Data Types.
Computer Science 1620 Loops.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Monday, 9/23/02, Slide #1 CS 106 Intro to CS 1 Monday, 9/23/02  QUESTIONS??  Today:  Discuss Lab 3  Do Exercises  Introduction to functions  Reading:
Computer Science 1620 Programming & Problem Solving.
CS0007: Introduction to Computer Programming Introduction to Arrays.
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.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
CS161 Topic #15 1 Today in CS161 Lecture #15 Practicing! Writing Programs to Practice Write a game program (1 player) of Mad Math Reuse the functions to.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction Structures are somewhat like an array in that.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 4: Continuing with C++ I/O Basics.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
DCT1063 Programming 2 CHAPTER 5 ADVANCED DATA TYPE (part 1) Mohd Nazri Bin Ibrahim Faculty of Computer Media and Technology TATi University College
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11. The Struct Data Type.
1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
Structures in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR.
Fundamental Programming: Fundamental Programming Introduction to C++
1 CS161 Introduction to Computer Science Topic #3.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
C++ Classes and Data Structures Jeffrey S. Childs
Structures (aka records, structs) Textbook Chapter 11 sections:
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
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.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Arrays.
1 CS161 Introduction to Computer Science Topic #15.
© Janice Regan, CMPT 128, Feb CMPT 128: Introduction to Computing Science for Engineering Students Structures.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
1 Introduction to Object Oriented Programming Chapter 10.
Fundamental Programming Fundamental Programming Introduction to Functions.
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Arrays Chapter 12. One-Dimensional Arrays If you wanted to read in 1000 ints and print them in reverse order, it would take a program that’s over 3000.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
CS 31 Discussion, Week 2 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:30-1:30pm (today)
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Structures  Structure types  Pointers and structure types  Structures.
Structures and Classes
Programmer Defined Types and Classes
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Structures Cont. Dr. Xiao Qin Auburn.
Programming Structures.
Student Book An Introduction
Structures Lesson xx In this module, we’ll introduce you to structures.
Learning Objectives Structures Structure types
One-Dimensional Array Introduction Lesson xx
Structures putting data together.
Programming Structures.
Programming Structures.
Presentation transcript:

 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures

Business  Exam 2 next week (Review on Wed)  Office hours will be next Thurs instead of Tues  Project 5 – Part A  Will discuss briefly on Monday  Due Monday, Nov 26 th  Also on Monday, you will complete Lab 8 (which we will start today). I will be in class until noon (at which time I have to leave for a meeting) 2

 Structures 3

 Prior knowledge – Arrays  Collection of multiple values of the same type  New concept – Structures  Collection of multiple values of different types  Treated as a single item, like arrays  Several key differences  Structure elements are accessed by name, not by index number  Must first define structure prior to declaring any variables 4

Why Structures?  The pieces of data are related in some way  Easier to keep them together (all in one place)  Easier to move them around all at once!  Examples  Certificate of Deposit at a bank  Account balance, interest rate, term length  Time of day  Hour, minute, second  Student information record  First name, last name, student ID number, cell phone, home phone, campus phone, etc… 5

New Keyword: struct  The keyword struct is used to create a new structure  Each item (member) inside the structure has a name, just like a variable  Two (or more) names to keep track of now  The name of the structure type  The name(s) of elements inside the structure 6

Define Structure Type  Define struct globally (typically)  Example for certificate of deposit account  Name of structure?  CDAccount  Name of members in the structure?  balance, InterestRate, term struct CDAccount { double balance; double interestRate; int term; }; 7

Declare Structure Variable  Step 1: Define structure type (previous slide)  Compiler then knows what a “CDAccount” is  Step 2: Declare a variable with this new structure type  Just like declaring an int, float, char, …  Variable account of type CDAccount  It contains “member variables” CDAccount account; 8

Accessing Structure Members  Individual elements are called “member variables”  Different structure types can have same member variable names without conflict  New operator to access members:.  Use to read or write a member variable 9 account.balance account.interestRate account.term A period! “dot”

Structures as Function Arguments  Passed like any simple data type  Pass-by-value or Pass-by-reference  Neat trick: Easily pass multiple data items to a function!  Can also be returned by function  Return type is structure type  Neat trick: Easily return multiple data items from a function! 10

Example Program 11 #include using namespace std; // Structure for certificate of deposit struct CDAccount { double balance; double interestRate; int term; }; CDAccount openAccount(void); void printAccount(CDAccount account); Function returning a struct Function taking a struct

Example Program 12 int main(void) { CDAccount account; account = openAccount(); printAccount(account); return 0; } Declare a new instance of the CDAccount structure called “account”

Example Program 13 CDAccount openAccount(void) { CDAccount account; cout << "Enter account balance: $"; cin >> account.balance; cout << "Enter account interest rate in %: "; cin >> account.interestRate; cout << "Enter number of months until maturity: "; cin >> account.term; return account; } Returns the variable account, which is a structure of type CDAccount and contains 3 member variables (balance, interestRate, and term)

Example Program 14 void printAccount(CDAccount account) { double rateFraction, interestEarned, endBalance; rateFraction = account.interestRate/100.0; interestEarned = account.balance* (rateFraction*(account.term/12.0)); endBalance = interestEarned + account.balance; cout << "When your CD matures in " << account.term << " months, it will have a balance of $" << endBalance << endl; }

Example Output 15 Enter account balance: $ Enter account interest rate in %: 10.0 Enter number of months until maturity: 6 When your CD matures in 6 months, it will have a balance of $105

Pitfall – Required Semicolon!  Semicolon after structure definition is required!  struct WeatherData { double temperature; double windVelocity; };  semicolon!  Required since you can declare structure variables in this location 16

Pitfall – Initialization  Member variables cannot be initialized in the declaration  The structure definition only defines the types, names and order of members  struct WeatherData { double temperature = 32.0; double windVelocity = 10; }; This is not allowed 17

Uniqueness of Names  Different structures may use the same member variables names without confusion  Names within a structure still have to be unique, however 18 struct CDAccount { double balance; double interestRate; int term; }; struct CheckingAccount { double balance; double interestRate; };

Structure Assignments  An entire structure can be copied in a single statement (in contrast to arrays, which must be element by element)  Declare two structure variables  CDAccount account1; CDAccount account2; // Set data in account1 account2 = account1;  Simply copies each member variable from apples into member variables from oranges  Can’t do anything else, however   No comparisons (==, >, <, etc.)  At least not without extra programming work… 19

Arrays of Structures  An array of 10,000 CD account structures  CDAccount accounts[10000];  Accessing an element of the structure in the array  cout << “Account #10 balance is $” << accounts[10].balance << endl;  Structures can have elements that are arrays, too 20

 Lab 8: Structures Exercise 21

Lab 8  You’re going to create a program to store information about a team of fencers at a tournament.  Create a Fencer structure to store the first name, weapon and scores from 2 bouts for each fencer. There are three possible weapons: “foil”, “epee” and “saber”. The scores for a bout are integers between 0 and

Lab 8  Create an array of 5 Fencers. This array should be declared in main(). You will pass it to functions that use it. (Remember that arrays are always passed by reference to functions).  Create a function to prompt the user for information about each fencer and fill it into the array  getTeam(Fencer team[], int teamSize);  Create a function to print out the name, weapon and highest score of each fencer on the team.  printTeam(Fencer team[], int teamSize); 23

Lab 8  Create a function to ask the user to select a weapon and then print out the names of all the fencers who use that particular weapon.  weaponChoice(Fencer team[], int teamSize);  Call these three functions in sequence inside main(). 24

Lab 8 25 Sample input and output

Questions? ? ? ? 26