Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C เรียงชื่อตามลำดับอักษรด้วย Structure


คำอธิบาย

ใช้ Structure เก็บข้อมูลนักเรียน (ชื่อ, เลขที่) แล้วเรียงลำดับตามชื่อ (Alphabetical order) ด้วย Bubble Sort และ strcmp()

การประกาศ Structure

struct tag {
    char name[10];
    int rno;
};
typedef struct tag node;
node s[5];

โค้ดตัวอย่าง

#include <stdio.h>
#include <string.h>

struct tag {
    char name[10];
    int rno;
};
typedef struct tag node;
node s[5];

void sort(int no) {
    int i, j;
    node temp;
    for (i = 0; i < no-1; i++)
        for (j = i+1; j < no; j++)
            if (strcmp(s[i].name, s[j].name) > 0) {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
}

int main() {
    int no, i;
    printf("Enter number of students: ");
    scanf("%d", &no);
    for (i = 0; i < no; i++) {
        printf("Enter name: ");
        scanf("%s", s[i].name);
        printf("Enter roll no: ");
        scanf("%d", &s[i].rno);
    }
    sort(no);
    for (i = 0; i < no; i++)
        printf("%s\t%d\n", s[i].name, s[i].rno);
    return 0;
}

ผลลัพธ์

Enter: 5 students
Priya 3
Hari 5
Pinky 7
Lucky 1
Krishna 2

Sorted:
Hari     5
Krishna  2
Lucky    1
Pinky    7
Priya    3