Lab 8: Arrays of Structs
In this lab you will be altering the following bit of code to use arrays of structs:
------------
/*
Arrays of Structs
You'll note that the code below does not actually use arrays of structs. You will be correcting this deficiency.
*/
#include <stdio.h>
#include <stdlib.h>
/*
Arrays of Structs
You'll note that the code below does not actually use arrays of structs. You will be correcting this deficiency.
*/
/*struct Person
{
Stuff goes here! */
//Takes in a given name, gender, and age and adds them to the three given arrays.
int readInValues(char nameArr[][15], char genderArr[], int ageArr[], int pCount)
{
if(pCount > 3)
{
printf("School is full. Try next year.");
return -1;
}
printf("Please enter a name: ");
scanf(" %14s", &nameArr[pCount][0]); //If you are wondering, the 14 is a maximum width specifier.
printf("\nPlease enter a gender(M or F): ");
scanf(" %c", &genderArr[pCount]);
printf("\nPlease enter an age: ");
scanf(" %d", &ageArr[pCount]);
return 0;
}
//Displays all stored values
void displayValues(int numStudents, char nameArr[][15], char genderArr[], int ageArr[])
{
int i;
printf("\n Current Students:");
for(i = 0; i < numStudents; ++i)
{
printf("\n%d . Name: %s, Gender: %c, Age: %d", i, nameArr[i], genderArr[i], ageArr[i]);
}
}
int main()
{
//Parallel arrays. If only we knew how to use an array of structs instead.
char firstName[4][15];
char gender[4];
int age[4];
char quit = '_';
int i = 0;
while(i < 4 && quit != 'Q')
{
readInValues(firstName, gender, age, i);
++i;
displayValues(i, firstName, gender, age);
printf("\n press 'Q' to quit, or any other letter to input another student.");
scanf(" %c", &quit);
}
return 0;
}
Stage 1 (1 point)
Change the program so that it uses an array of structs to store all the information instead of the parallel arrays. The other functions do not need to work with the new storage method.
Stage 2 (1 point):
Modify readInValues and displayValues so that they work with the new array of structs
Stage 3 (Extra Credit, 1 point):
Modify the code so that the students are printed out in alphabetical order (first to last).
Notes:
More examples can be found here: http://en.wikipedia.org/wiki/Struct_(C_programming_language)
Submission:
You should work with a partner for a grade. Only one submission per group is necessary, but be sure to include your name if you work alone, or both people's names if you worked with a partner.
You should submit the lab to the Blackboard at the end of the lab session, by 50 minutes after the hour.