Download presentation
Presentation is loading. Please wait.
1
Structures December 6, 2017
2
Structures Suppose you want to make a program to keep track of some basic information about every student at THS: Name Date of birth State ID GPA Now consider how many variables you would need to do this (hint: a lot). Isn’t there an easier way???? Create a structure!
3
Structures A structure is a collection of variables of different data types under a single name. It may help to think of a structure as an array with different data types. In reality, structures are significantly more nuanced, but we will largely be using them in this way.
4
Structures The following syntax is used to declare a structure:
struct Date { int month; int day; int year; string day_of_week; }; Note the semicolon after the closing curly brace!
5
Structure Syntax struct Date { int month; int day; int year; string day_of_week; }; This syntax declares a structure with name Date. Every Date in turn has four “sub-variables”: month, day, year, and day_of_week. These “sub-variables” are known as member variables.
6
Structure Syntax The following will declare three variables of type Date: Date yesterday, today, tomorrow; Each of these three variables has four member variables: month, day, year, and day_of_week. It may help to think of this as creating three “mixed arrays” with four entries in each: month, day, year, and day_of_week.
7
Structure Syntax To access a member variable, use the dot operator:
yesterday.month = 12; yesterday.day = 5; yesterday.year = 2017; yesterday.day_of_week = "Tuesday"; This can also be done using curly braces, like with an array: Date yesterday = {12, 5, 2017, "Tuesday"};
8
Structure Syntax For today, the syntax is (essentially) the same:
today.month = 12; today.day = 6; today.year = 2017; today.day_of_week = "Wednesday"; Using a single line: Date today = {12, 6, 2017, "Wednesday"};
9
Structure Syntax Consider the following syntax:
today = tomorrow; This is equivalent to the following: today.month = tomorrow.month; today.day = tomorrow.day; today.year = tomorrow.year; today.day_of_week = tomorrow.day_of_week;
10
Structure Syntax struct Date { int month; int day; int year; };
struct PersonInfo double height; int weight; Date birthday;
11
Structure Syntax Consider the following syntax:
ShoeType shoe1, shoe2; shoe1.style = 'A'; shoe1.price = 9.99; cout << shoe1.style << " $" << shoe1.price << endl; shoe2 = shoe1; shoe2.price = shoe2.price / 9; cout << shoe2.style << " $" << shoe2.price << endl; Assuming style is a char and price is a double, what is the output?
12
Structure Syntax Answer: A $9.99 A $1.11
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.