after editing
the code is :
#include <stdio.h>
#include <string.h>
struct names//defining struct array with leinght of (3)
{
char firstname[50];
char lastname[50];
int age;
}n[4];
void show(struct names n[],int);//print the struct elements on the screen
void sortbyage(struct names n[],int);//sort the struct elements by age
int main(void)
{
struct names n[4];
int len=3;
strcpy(n[0].firstname,"david");
strcpy(n[0].lastname,"bekham");
n[0].age=18;
strcpy(n[1].firstname,"cristiano");
strcpy(n[1].lastname,"ronaldo");
n[1].age=20;
strcpy(n[2].firstname,"iron");
strcpy(n[2].lastname,"man");
n[2].age=16;
show(n,len);
sortbyage(n,len);
show(n,len);
return 0;
}
void show(struct names n[],int len)
{
for(int i=0;i<3;i++)
{
printf("%d-first name ==>%s\n",i+1,n[i].firstname);
printf("%d-last name ==>%s\n",i+1,n[i].lastname);
printf("%d-age==>%i\n",i+1,n[i].age);
}
}
void sortbyage(struct names n[],int len)
{
// int help=0;
for(int i=len-1;i>0;i--)
{
for(int j=0;j<i;j++)
{
if(n[j].age>n[j+1].age)
{
n[4]=n[j];
n[j]=n[j+1];
n[j+1]=n[4];
}
}
}
}
after Editing it works
note : in run time it types in the last line this message : * process returned -1073741819 *)) how could I fix this and does it a big problem or it's don't matter???
You need to access as follows. Please modify your code some thing as below
if(n[j].age > n[j+1].age)
Hope this helps.
Edit: Please modify the sortbyage() function as follows and it is working fine.
void sortbyage(struct names n[],int len)
{
struct names temp;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(n[i].age > n[j].age)
{
temp = n[i];
n[i] = n[j];
n[j] = temp;
}
}
}
}