Hi all,
Having some trouble with an assignment. My program should store lists of names and ages and sort the list by name (alphabetic).

Here's my current attempt


// struct to hold the data
typedef struct _data
	char name[5][30];
	int age[5];
} data;

int main()
	data s;

	int i, j;

	char temps[30];
	int tempa;

	printf("Enter values, name then age>\n");

	for(i=0;i<5;i++)	// get user inputs

	// bubble sort to get alphabetized list
			if( strcmp(s.name[i],s.name[i+1]) >0)	// if bigger
				// swap names
				strcpy(temps, s.name[i]);
				strcpy(s.name, s.name[i+1]);
				strcpy(s.name[i+1], temps);

				// swap ages
				tempa = s.age[i];
				s.age[i] = s.age[i+1];
				s.age[i+1] = tempa;

	printf("\nAplhabetised List>\n");

		printf("%s %d\n",s.name[i], s.age[i]);
}	// end main

It's giving me really strange results, any idea what's up with it? It's my first time using a struct :$ so is the problem there?

Thanks in advance

line 6 is wrong scanf("%d", &s.age[i]); And the sort algorithm needs some twinking. line 34: Its not necessary to check from 0 to current value of j because they are already in order. for(i=i+1;i<5;i++) And the swaps should use j and i, not i and i+1.

This article has been dead for over six months. Start a new discussion instead.