C language programming (Chapter 8 establishing data types)

C language programming (Chapter 8 establishing data types)

1, Defining and using structure variables

1. Create your own structure type

C language allows users to establish a combined data structure composed of different types of data, which is called structure
numbernamesexagescoreaddr
10010luxinanM1987.5Beijing
If you want to use the data structure represented by this table in the program, you can create a structure type yourself in the program
struct Student{
	int number;				//Student number is integer
	char name[20];			//Name is a string
	char sex;				//Gender is character type
	int age;				//Age is integer
	float score;			//The result is real
	char addr[30];			//The address is a string
}

The above program specifies a structure type struct Student (struct is a keyword that must be used when declaring a structure type and cannot be omitted). The general form of declaring a structure type is:

struct structural morphology
{Member table column};

Within the curly braces are the sub items included in the structure, which are called members of the structure. The above number, name, sex, etc. are members. Type declaration should be made for each member, i.e

Type name member name;

Members can belong to another structure type, for example:

struct Date{			//Declare a struct type struct Date
	int month;			//month
	int day;			//day
	int year			//year
}

struct Student{
	int num;
	char name[20];
	char sex;
	int age;
	struct Date birthday;			//The member birthday is of type struct Date
	char addr[30];
}

2. Define structure type variables

(1) Declare the structure type first, and then define the type variable
struct Student student1,student2;
Structure type name           Two structure variable names

This form and defines other types of variable forms (e.g., int, a, B;) Is similar. The above defines student1 and student2 as variables of struct Student type, so that student1 and student2 have struct Student type structures.

(2) Define variables while declaring types
For example:
struct Student
{
	int num;
	char name[20];
	char sex;
	int age;
	float score;
	char addr[30];
} student1,student2;

Its function is the same as that of the first method, but when defining the struct Student type, it also defines the variables student1 and student2 of two struct Student types. The general form of this definition method is

struct Structure name
{
Member table column
}Variable name table column;
(3) Structure type variables are defined directly without specifying a type name

Its general form is

struct
{
Member table column
}Variable table column;

3. Initialization and reference of structure variables

When defining a structure variable, you can initialize it, that is, give it an initial value. You can then reference this variable, such as outputting the value of its member.

Example 1: put a student's information (including student number, name, gender and address) into a structural variable, and then output the student's information.
#include <stdio.h>
int main(){
    struct Student{
        long int num;
        char name[20];
        char sex;
        char addr[20];
    } a={10101,"Lu",'M',"Beijing"};
    printf("NO.:%1d\nname:%s\nsex:%c\naddr:%s\n",a.num,a.name,a.sex,a.addr);
    return 0;
}

Operation results:

NO.:10101
name:Lu
sex:M
addr:Beijing
(1) C99 standard allows initialization of a member, such as:
struct Student b={.name="Zhang san"};

". name" implicitly represents the member b.name of structure variable B. Other numeric members that are not initialized are initialized to 0, character members are initialized to '\ 0' and pointer members are initialized to NULL.

(2) You can reference the value of the member in the structure variable by
Structure variable name.member name

In the program, you can assign values to the members of variables, such as:
student1.num=10010;
(3) If the member itself belongs to a structure type, you need to use several member operators to find the members of the lower level one by one. Only the lowest level members can be assigned or accessed and operated. If the member of struct Student type contains another member of struct date type birthday, the method of referencing the member is
student1.num							//Member num in struct variable student1
student1.birthday.mounth				//Member month in birthday in struct variable student1

Cannot use student1 Birthday to access the member birthday in the student1 variable, because birthday itself is a structural member.

(4) Members of structural variables can perform various operations like ordinary variables (the operations that can be performed are determined according to their types). for example
student2.score=student1.score;				//Assignment operation
sum=student1.score+student2.score;			//Addition operation
student1.age++;								//Self addition operation
(5) Structural variables of the same kind can be assigned to each other, such as:
student1=student2;
(6) You can refer to the address of the structural variable member or the address of the structural variable. For example:
scanf("%d",&student1.score);		//Enter student1 Value of score
printf("%o",&student1);				//The starting address of the output structure variable student1
Example 2: input the student number, name and grade of two students, and output the student number, name and grade of students with higher grades.
#include <stdio.h>
int main(){
    struct Student{
        int num;
        char name[20];
        float score;
    }student1,student2;
    scanf("%d%s%f",&student1.num,&student1.name,&student1.score);
    scanf("%d%s%f",&student2.num,&student2.name,&student2.score);
    printf("The higher score is:\n");
    if(student1.score>student2.score){
        printf("%d  %s  %6.2f",student1.num,student1.name,student1.score);
    }
    else if(student2.score>student1.score){
        printf("%d  %s  %6.2f",student2.num,student2.name,student2.score);
    }
    else{
        printf("%d  %s  %6.2f",student1.num,student1.name,student1.score);
        printf("%d  %s  %6.2f",student2.num,student2.name,student2.score);
    }
    return 0;
}

Operation results:

input:
    01 zhangsan 89.1
	02 lisi 90

output:
2  lisi  90.00

2, Use structure array

Example 3: there are three candidates, and each voter can only vote for one person. It is required to compile a procedure for counting votes, input the names of the candidates successively, and finally output the results of each person's vote.
#include <stdio.h>
#include <string.h>
struct Person{
    char name[20];
    int count;
}leader[3]={"zhangsan",0,"lisi",0,"wangwu",0};

int main(){
    int i,j;
    char leader_name[20];
    for(i=1;i<=10;i++){
        scanf("%s",leader_name);
        for(j=0;j<3;j++){
            if(strcmp(leader_name,leader[j].name)==0) leader[j].count++;
            //strcmp in c language means the abbreviation of string compare. It is used to compare two strings and return integers according to the comparison results. The basic form is strcmp(str1,str2). If [str1=str2], it returns zero. If [str1=str2], it returns zero
        }
    }
    printf("\nResult:\n");
    for(i=0;i<3;i++){
        printf("%5s:%d\n",leader[i].name,leader[i].count);
    }
    return 0;
}

Operation results:
	input:
zhangsan
lisi
wangwu
wangwu
zhangsan
lisi
lisi
lisi
zhangsan
zhangsan
    
    output:
Result:
zhangsan:4
 lisi:4
wangwu:2
(1) Define the general form of structure array:
1.struct Structure name
{Member table column} Array name[Array length];

2.Specify a structure type first (e.g struct Person),Then use this type to define the structure array:
	Structure type	Array name[Array length];
as:
	struct Person leader[3];
(2) The form of initializing the structure array is to add the following after defining the array:
={Initial value table column};

struct Person leader[3]={"zhangsan",0,"lisi",0,"wangwu",0};
Example 4: there are n students' information (including student number, name and grade). It is required to output the information of each student in the order of grade
#include <stdio.h>
struct Student{
    int num;
    char name[20];
    float score;
};

int main(){
    struct Student stu[5]={{1001,"zhangsan",87.5},{1002,"lisi",97.3},{1003,"wangwu",78.4},{1004,"zhaoliu",98.3},{1005,"liuqi",69.5}};
    struct Student temp;
    const int n=5;
    int i,j,k;
    printf("The order is:\n");
    for(i=0;i<n-1;i++){
        k=i;
        for(j=i+1;j<n;j++){
            if(stu[j].score>stu[k].score)
            k=j;
        }
        temp=stu[k];stu[k]=stu[i];stu[i]=temp;
    }
    for(i=0;i<n;i++){
        printf("%6d %8s %6.2f\n",stu[i].num,stu[i].name,stu[i].score);
    }
    return 0;
}

Operation results:

The order is:
  1004  zhaoliu  98.30
  1002     lisi  97.30
  1001 zhangsan  87.50
  1003   wangwu  78.40
  1005    liuqi  69.50

Keywords: C Back-end

Added by itaym02 on Sat, 26 Feb 2022 09:07:29 +0200