Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 100

C Exercise 100

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** There are five students, each with grades in 3 courses. Enter the above data from the keyboard (including student number, name, and the three grades), calculate the average grade, and store the original data along with the calculated average in the disk file "stud".

**Analysis:** None.

Program source code:

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. 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 enter the information for 5 students: student number, name, 3 grades:

\

n

"

)

;

for

(

i

=

0

;

i

<

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

<

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, the output is:



Please enter information for 5 students: Student ID, Name, 3 grades:

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

Open the stud file; its contents are 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

100 Classic C Language Examples 100 Classic C Language Examples