I almost have it. This program will take the struct person student[] which contains 5 students it will first print the students and then it will sort them by age.
I have written the print_person_info and I have almost finished sort_by_age.
But I get the error: incompatible types when assigning struct person from int and incompatible types when assigning int from struct person.
I have a feeling I need to use pointer notation. ex. (&, *) in front of temp. But I am not sure how to use the notation..thank you for your help.
Code:
#include <stdio.h>
struct person
{
char first_name[20];
char last_name[20];
int age;
};
void print_person_info(struct person clone);
void sort_by_age(int n, struct person a[]);
int main(void)
{
int i, n=5;
struct person student[5] =
{
{ "Bob", "Smith", 21},
{ "Jimmy", "John", 18},
{ "Amy", "Goldberg", 20},
{ "Dan", "Marlo", 17},
{ "Sally", "Sorrow", 16}
};
for(i=0; i<n; i++)
print_person_info(student[i]);
sort_by_age(n, student);
printf("------AFTER SORTING-------\n");
for(i=0; i<n; i++)
print_person_info(student[i]);
return 0;
}
void print_person_info(struct person clone)
{
int i=0;
for(i=0; i<5;i++)
{
printf("First Name: %s Last Name: %s Age: %d \n", clone.first_name, clone.last_name, clone.age);
}
}
void sort_by_age(int n, struct person a[])
{
int i=0, j, temp;
for(i=0; j<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(student[i].age > student[j].age)
{
temp =student[i].age;
student[i].age=student[j].age;
student[j].age=temp;
}
}
}
}