Easy Tutorial
❮ C Exercise Example10 C Function Ctime ❯

C Practice Example 100

C Language Classic 100 Examples

Title: There are five students, each with scores for three courses. Input the data (including student ID, name, and scores for three courses) from the keyboard, calculate the average score, and store the original data along with the calculated average scores in the disk file "stud".

Program Analysis: None.

Program Source Code:

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include<stdio.h>
#include<stdlib.h>
typedef struct{
    int ID;
    int math;
    int English;
    int C;
    int avargrade;
    char name[20];
}Stu;
int main()
{
    FILE*fp;
    Stu stu[5];
    int i,avargrade=0;
    printf("Please input information for 5 students: student ID, name, and scores for 3 courses:\n");
    for(i=0;i&lt;5;i++)
    {
        scanf("%d %s %d %d %d",&(stu[i].ID),stu[i].name,&(stu[i].math),&(stu[i].English),&(stu[i].C));
        stu[i].avargrade=(stu[i].math+stu[i].English+stu[i].C)/3;
    }

    if((fp=fopen("stud","w"))==NULL)
    {
        printf("error :cannot open file!\n");
        exit(0);
    }
    for(i=0;i&lt;5;i++)
        fprintf(fp,"%d %s %d %d %d %d\n",stu[i].ID,stu[i].name,stu[i].math,stu[i].English,
                stu[i].C,stu[i].avargrade);

    fclose(fp);
    // system("pause");
    return 0;
}

After running the above example and outputting the results:

Please input information for 5 students: student ID, name, and scores for 3 courses:
1 a 60 70 80
2 b 60 80 90
3 c 59 39 89
4 e 56 88 98
5 d 43 88 78

Opening the "stud" file, the content is as follows:

1 a 60 70 80 70
2 b 60 80 90 76
3 c 59 39 89 62
4 e 56 88 98 80
5 d 43 88 78 69

C Language Classic 100 Examples

❮ C Exercise Example10 C Function Ctime ❯