โจทย์
เก็บข้อมูลนักตีลูก: ชื่อ, อายุ, นัดที่เล่น, คะแนนเฉลี่ย แล้วจัดเรียงตามคะแนนเฉลี่ยน้อยไปมาก
โครงสร้าง Struct
struct cricketer {
char name[50];
int age;
int matches;
float avgRuns;
char temp; // for newline
};
ตรรกะการจัดเรียง (Bubble Sort)
for(i=0; ic[j].avgRuns) { temp = c[i]; c[i] = c[j]; c[j] = temp; } } }
โปรแกรมตัวอย่าง
#include <stdio.h>
#include <string.h>
struct cricketer {
char name[50];
int age;
int matches;
float avgRuns;
char temp;
};
int main() {
struct cricketer c[20], temp;
int i, j;
for(i = 0; i < 2; i++) {
printf("Cricketer %d\n", i+1);
printf("Name: "); fgets(c[i].name, 50, stdin);
c[i].name[strcspn(c[i].name, "\n")] = 0;
printf("Age: "); scanf("%d", &c[i].age);
printf("Matches: "); scanf("%d", &c[i].matches);
printf("Avg Runs: "); scanf("%f", &c[i].avgRuns);
scanf("%c", &c[i].temp); // consume newline
}
// Sort by avgRuns ascending
for(i = 0; i < 2; i++) {
for(j = i+1; j < 2; j++) {
if(c[i].avgRuns > c[j].avgRuns) {
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
printf("\nSorted by Average Runs:\n");
for(i = 0; i < 2; i++) {
printf("%d\t%s\t%d\t%d\t%.2f\n", i+1, c[i].name, c[i].age, c[i].matches, c[i].avgRuns);
}
return 0;
}
ผลลัพธ์
Enter data of cricketer 1 Name: Dhoni Age: 39 Matches: 150 Average runs: 200 Enter data of cricketer 2 Name: Virat Age: 36 Matches: 135 Average runs: 190 Sorted records: 1 Virat 36 135 190.00 2 Dhoni 39 150 200.00