CS 1440 Lab 7

Cover sheetPrevious ActivityNext Activity


Activity 7-1: C++ struct data type

Activity Goals

        To define a struct

        To use structs in various C++ expressions

Activity Procedure

Examine the following C++ program that defines and uses the Student struct described in the prelab.
Especially notice:

1.      How the struct is defined,

2.      Where the struct is defined,

3.      How the struct variables are used

a.       as function parameters

b.      in I/O statements

c.       in arithmetic expressions.

 

#include  <iostream>
#include  <string>

/* struct definition BEFORE any use of Student */
struct  Student
{
     string  name;
     string  grade;
     double  test1, test2, test3;
     double  average;
};

void  get_info(Student &s);  /* Student data type already defined */
void  print_info(Student s);

int main(void)
{
     int s;
     Student  student1, student2;  /* Student data type
                                      already defined */

     get_info(student1);
     get_info(student2);
     do {
          cout << "Which student info do you wish to see? (1 or 2): ";
          cin >> s;
     }while ( ! (s==1 || s==2));
     if (s == 1) print_info(student1);
     else        print_info(student2);
}

void  get_info(Student & s)  /* Notice reference parameter!! */
{
     cout  <<  "Enter student’s last name: ";
     cin >> s.name;
     cout  <<  "Enter 3 test scores: ";
     cin >> s.test1 >> s.test2 >> s.test3;
     s.average = (s.test1 + s.test2 + s.test3) / 3;
     cout  <<  "Enter final letter grade: ";
     cin >> s.grade;
}

void  print_info(Student s)
{
     cout  <<  "Student: "  <<  s.name  <<  endl;
     cout  <<  "\tGrade: "  <<  s.grade  <<  endl;
     cout  <<  "\tTests: "  <<  endl;
     cout  <<  "\t\tAverage: "  <<  s.average  << endl;
     cout  <<  "\t\tScores: "
           <<  s.test1  <<  ","
           <<  s.test2  <<  ","
           <<  s.test3  << endl;
}

Activity Followup

Make a Lab7 directory in your 1440 directory.

Cut and paste the above program into a file named struct.C in your Lab7 directory.

Modify the program in the following ways:

1.      Define a struct  “Course”  that consists of a department code (like “CS” or “CHE”), a course number (like 1440), and a section number (like 103).

2.      Change the Student struct to include 2 courses being taken by the student (these are part time students!)

3.      Change the get_info and print_info functions as necessary to accommodate the courses students are taking.