/* This program demonstrates * 1. An introduction to structures * 2. Nested Structs * * A structure is a way to create a composite data type. * So far, we have been working with atomic/primitive data types that can only * hold one kind of data. structures allow us to bundle up several data elements * into one unit, while still allowing us to access the individual elements. * A structure can be used as a regular data type. * * We can create variables of the structure type, pass it to functions and * return it from functions * With respect to functions, struct variables pass by value. * * This program also demonstrates advanced struct concepts * 1. Structs can contain arrays as data elements * 2. Structs can be nested - ie structs can contain other struct variables */ #include #include #include using namespace std; /* To create a structure, we use the keyword "struct" followed by the name of the * structure (we choose this). We then open a code block and declare all the variables * for the elements of the structure. * We only declare them. Structure elements should NOT be initialized (given values) * in the structure declaration unless they are consts. * the structure declaration ends with a semicolon. * The following line declares a Date structure with 4 data members */ struct Date { int month, day, year; char dayOfWeek[15]; }; /* Student structure * name - string * major - string * GPA - float * EMPL - long * grades - array of 3 floats * datOfBirth - Date struct variable */ struct Student { string name, major; float gpa; long empl; float grades[3]; Date dateOfBirth; }; // If a function uses a structure, it has to be declared after the struct declaration void printDate(Date d); Date readDate(); void printStudent(Student s); void readStudent( Student &s); int main() { /* To declare a structure variable, just use the Structure name as a data type. * Just like an array can be initialized with set notation, we can initialize * structures with set notation as well. Any composite types in the structure * (like arrays, other structures) need their own set of {} */ Date today = {11, 15, 2021, "Monday"}; /* To access an internal element of the structure variable, we use the dot (.) operator */ cout<<"Today is "<< today.dayOfWeek<<", "<< today.month<<"/"<< today.day <<"/"<< today.year<>var.month>> junk>> var.day>>junk>>var.year; return var; } /* This function accepts a structure variable and prints out the details in the structure * We use the dot (.) operator to access individual elements. */ void printStudent( Student s) { cout<>s.gpa; cout<<"EMPLID: "; cin>>s.empl; cout<<"3 grades: "; for(int i=0; i<3;i++) cin>>s.grades[i]; cout<<"Date of birth (Day of Week, m/d/y): "; cin.getline(s.dateOfBirth.dayOfWeek, 15, ','); cin>>s.dateOfBirth.month; cin.ignore(); cin>>s.dateOfBirth.day; cin.ignore(); cin>>s.dateOfBirth.year; }