使用結構體按字母順序排序名稱的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.