// Struct example - student record
// 

#include <iostream.h>


// here we define the struct.
// This tells the compiler about the new type StudentRecord, but
// doesn't result in any variables being allocated memory.

struct StudentRecord {
  char *name;		// student name
  double hw[3];		// homework grades
  double test[2];	// test grades
  double ave;		// final average
};


void print_student( StudentRecord s ) {

  cout << "Name: " << s.name << endl;

  for (int i=0;i<3;i++) 
    cout << "HW #" << i << ": " << s.hw[i] << endl;

  for (int i=0;i<2;i++) 
    cout << "TEST #" << i << ": " << s.test[i] << endl;

  cout << "Average: " << s.ave << endl;
}


// this won't work - the struct is passed by value,
// so we get a copy (and the original will not be updated).
//
// NOTE: You can get this to work by changing the parameter to
// be a reference parameter!

void update_average( StudentRecord stu) {
  double tot=0;

  for (int i=0;i<3;i++)
    tot += stu.hw[i];
  for (int i=0;i<3;i++)
    tot += stu.test[i];
  stu.ave = tot/5;
}


// this will work - we use a pointer to a struct instead
void update_average( StudentRecord *stu) {
  double tot=0;

  for (int i=0;i<3;i++)
    tot += stu->hw[i];
  for (int i=0;i<3;i++)
    tot += stu->test[i];
  stu->ave = tot/5;
}



int main(void) {
  // declare a variable of type StudentRecord

  StudentRecord stu;

  // initialize with some stuff

  stu.name = "Joe Student";
  stu.hw[0] = 90.5;
  stu.hw[1] = 100;
  stu.hw[2] = 55.25;


  stu.test[0] = 82.5;
  stu.test[1] = 88;


  //print the record - note that we haven't set the average yet!
  print_student(stu);

  // now call the bad average function (that doesn't work).
  update_average(stu);

  //print the stu - note that we still haven't set the average yet!
  print_student(stu);

  // now try with a pointer
  update_average(&stu);

  //print the stu - note we now have an average
  print_student(stu);


  return(0);
}


  

