how to print a whole row from an array?
I wrote a program which shows the data about 5 students I want to know how 开发者_如何学编程to show the student name registration number and marks who obtained highest marks in the array. The program is like that:
#include "stdio.h"
#include "conio.h"
struct student
{
char name[30];
char reg[10];
short int marks_dbms;
short int marks_prog;
};
void main()
{
short int i;
student a[5]={
{"salman","B-1499",92,98},
{"Haider","B-1489",34,87},
{"zeeshan","B-1897",87,90},
{"faizan","B-1237",56,66},
{"Asif","B-1233",88,83}
};
for(i=0; i<5; i++)
{
printf("%s\t",a[i].name);
printf("%s\t",a[i].reg);
printf("%d\t",a[i].marks_dbms);
printf("%d\t\n",a[i].marks_prog);
}
getch();
}
Thats a simple one.
int maxDbmsMarks = 0;
int maxMarksIndex = 0;
for(int i = 0; i < 5; i++)
{
if(a[i].marks_dbms > maxDbmsMarks )
{
maxDbmsMarks = a[i].marks_dbms;
maxMarksIndex = i;
}
}
printf("Student with the maximum dbms marks :\n");
printf("Name : %s, Reg : %s, dbmsMarks: %d, progMarks : %d\n", a[maxMarksIndex].name, a[maxMarksIndex].reg, a[maxMarksIndex].makrs_dbms, a[maxMarksIndex].marks_prog);
It is the same as finding the maximum number in an array. The above logic is for 'highest dbms marks', you can modify it to find the highest prog marks or highest combined marks.
First, write a function to compare students by their marks. It should accept two student parameters, and return true if the first student should be considered less than the second.
bool compareStudentsByMarks(const student & lhs, const student & rhs)
{
// This only compares by marks_dbms, I'm not sure how you want to do it.
return lhs.marks_dbms < rhs.marks_dbms;
}
Then, after including the <algorithm>
header, use the function std::max_element
, passing your function as the last argument.
const int SIZE_OF_STUDENT_ARRAY = 5;
student * pmax = std::max_element(a, a+SIZE_OF_STUDENT_ARRAY, compareStudentsByMarks);
// now pmax is a pointer to the student with the highest marks,
// you already know how to display their info
If you have access to C++0x, this is all a lot easier:
auto pmax = std::max_element(a, a+SIZE_OF_STUDENT_ARRAY,
[](const student & lhs, const student & rhs)
{
return lhs.marks_dbms < rhs.marks_dbms;
});
精彩评论