C语言实现学生信息表插入并排序
C语言实现学生信息表插入并排序
本代码使用C语言实现了一个学生信息表,包含学号、姓名、性别、年龄等信息,并提供插入新学生信息的功能,同时保证信息按照学号升序排列。
结构体定义
typedef struct Student{
int sno;
char name[10];
char sex;
int age;
}Student;
typedef struct Table{
Student stu[1000];
int num;
}Table;
代码实现
#include<stdio.h>
#include<string.h>
typedef struct Student{
int sno;
char name[10];
char sex;
int age;
}Student;
typedef struct Table{
Student stu[1000];
int num;
}Table;
int main(){
Table table;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %s %c %d",&table.stu[i].sno,&table.stu[i].name,&table.stu[i].sex,&table.stu[i].age);
}
scanf("%d %s %c %d",&table.stu[n].sno,&table.stu[n].name,&table.stu[n].sex,&table.stu[n].age);
n++;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(table.stu[i].sno>table.stu[j].sno){
Student temp=table.stu[i];
table.stu[i]=table.stu[j];
table.stu[j]=temp;
}
}
}
for(int i=0;i<n;i++){
printf("%d %s %c %d\n",table.stu[i].sno,table.stu[i].name,table.stu[i].sex,table.stu[i].age);
}
return 0;
}
代码说明
- 首先定义了
Student和Table结构体,分别用于存储单个学生信息和整个学生信息表。 - 然后在
main函数中,首先读取学生人数n,并依次读取每个学生的信息并存储到table.stu数组中。 - 接着,读取要插入的新学生信息,并将其存储到
table.stu[n]中。 - 使用嵌套循环对
table.stu数组进行排序,使用冒泡排序算法,保证信息按照学号升序排列。 - 最后,将排序后的学生信息输出。
总结
本代码使用C语言实现了学生信息表插入并排序的功能,代码简洁易懂,并提供了详细的注释,方便理解。该代码可以作为学习C语言数据结构和算法的参考示例。
原文地址: https://www.cveoy.top/t/topic/ojLE 著作权归作者所有。请勿转载和采集!