使用结构体按字母顺序排序名称的C程序


结构体是不同数据类型变量的集合,这些变量在一个名称下组合在一起。

结构体的特性

C 编程语言中,结构体的特性如下:

  • 可以使用赋值运算符将不同数据类型的所有结构体元素的内容复制到另一个相同类型的结构体变量中。

  • 为了处理复杂的数据类型,最好在一个结构体中创建另一个结构体,这称为嵌套结构体。

  • 可以将整个结构体、结构体的单个元素以及结构体的地址传递给函数。

  • 可以创建指向结构体的指针

结构体的声明和初始化。

结构体声明的一般形式如下:

datatype member1;
   struct tagname{
      datatype member2;
      datatype member n;
};

这里,

  • struct 是关键字。
  • tagname 指定结构体的名称。
  • member1, member2 是数据项。

例如,

struct book{
   int pages;
   char author [30];
   float price;
};

程序

以下是 **使用结构体按字母顺序排序名称的C程序**:

 在线演示

#include<stdio.h>
#include<string.h>
struct tag{
   char name[10];
   int rno;
};
typedef struct tag node;
node s[5];
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;
   }
}
void main(){
   int no,i;
   fflush(stdin);
   printf("Enter The Number Of Students:");
   scanf("%d",&no);
   for(i=0;i<no;i++){
      printf("Enter The Name:");
      fflush(stdin);
      gets(s[i].name);
      printf("Enter the Roll:");
      scanf("%d",&s[i].rno);
   }
   sort(no);
   for(i=0;i<no;i++){
      printf("%s\t",s[i].name);
      printf("%d
"
,s[i].rno);    } }

输出

执行上述程序时,将产生以下结果:

Enter The Number of Students:5
Enter The Name:Priya
Enter the Roll:3
Enter The Name:Hari
Enter the Roll:5
Enter The Name:Pinky
Enter the Roll:7
Enter The Name:Lucky
Enter the Roll:1
Enter The Name:Krishna
Enter the Roll:2
Hari 5
Krishna 2
Lucky 1
Pinky 7
Priya 3

更新于: 2023年9月2日

5K+ 浏览量

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.