HELP! it seems my output only compare 2 element. Any1 can help me fix and tell me the problems much appreciated.
Write a program to read 5 person's name and age from the keyboard and save them into memory using arrays. Display the list starting with the youngest person to the oldest. Assume all names are single words. Name are to be left justified while age are right justified.
A sample output of the program :
Enter 5 names:
Enter name and age for person 1 : Kim 23
Enter name and age for person 2 : Jason 18
Enter name and age for person 3 : Lee 14
Enter name and age for person 4 : Dan 34
Enter name and age for person 5 : May 8
The sorted list is :
Name Age
May 8
Lee 14
Jason 19
Kim 23
Dan 34
First, the use of code tags and intuitive indentation really helps to see what is in the posted code.
See http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post to add the tags.
Second, juggling with multiple arrays is possible (and perhaps educative), but there is an another approach: structures. A single array can store complex data, if each element is a structure that holds various attributes. It makes the code look simpler too, because we can hide the gory details elsewhere.
Along the same lines we like to move some operations into functions. For example, the standard library offers a 'swap' function:
1 2 3 4 5 6 7 8 9 10 11
if ( name[ index[i] ] < name[ index[j] ] )
{
temp = index[i];
index[i] = index[j];
index[j] = temp;
}
// could be written
if ( name[ index[i] ] < name[ index[j] ] )
{
std::swap( index[i], index[j] );
}
while that seems to save only two lines here (and the swap-function has some lines too, increasing the total length of code) it should be crystal clear that we exchange values. Shorter and more expressive.
The structs. The data attributes describe a person, so we could have a
Observations so far: all of the for lppos are written i <= 4
This works, but usually written i < 5
or you could say i < limit
since you already have a const value with limit why not use it.
The sort routine does work, but you are sorting names when you need to sort by ages. Also it sorts in reverse order, not what you want.
Hope that helps some,
Andy
P.S. please edit your post and put the code tag <> (under format:) aroung uour code. It makes it easier to read.