diff --git a/cs161BW9/insertingNameInPlace.cpp b/cs161BW9/insertingNameInPlace.cpp new file mode 100644 index 0000000..c4aeeac --- /dev/null +++ b/cs161BW9/insertingNameInPlace.cpp @@ -0,0 +1,76 @@ +#include +#include +using namespace std; + +const int maxchar = 30; +const int maxstudents = 25; + + +struct Student{ + char first[maxchar]; + char last[maxchar]; + float gpa; +}; + +struct Course{ + Student roster[maxstudents]; + int studentCount; +}; + +void insertArray(Student s, Student r[], int i, int count){ + // first we make room in the array + for(int j = count; j >= i; j--){ + r[j+1] = r[j]; + } + r[i] = s; +} + +void addStudent(Student s, Course &c){ + int i=0; + bool found=false; + while(i < c.studentCount && !found) { + if(strcmp(s.last, c.roster[i].last) > 0){ + i++; + } + else{ + found=true; + } + } + insertArray(s,c.roster, i,c.studentCount); + c.studentCount++; +} + +void printCourse(Course c){ + for(int i =0; i < c.studentCount; i++){ + cout << c.roster[i].first << ";"; + cout << c.roster[i].last << ";"; + cout << c.roster[i].gpa << endl; + } +} + +int main(){ + char temp[maxchar]; + cout << "Enter a student's first name or type exit to exit" << endl; + cin >> temp; + + Course newCourse; + newCourse.studentCount = 0; + + + while(cin && strcmp(temp,"exit") != 0){ + Student newStudent; + strcpy(newStudent.first,temp); + cout << "Enter a student's last name" << endl; + cin >> temp; + strcpy(newStudent.last,temp); + cout << "Enter student grade" << endl; + cin >> newStudent.gpa; + + addStudent(newStudent, newCourse); + + printCourse(newCourse); + + cout << "Enter a student's first name or type exit to exit" << endl; + cin >> temp; + } +}