pc014.c (1720B)
1 /* Write a c program that defines a structure Student with the following members: roll (int), name (string), and marks (float). 2 Do the below: 3 * Create an array to store details for 3 students. 4 * Read the details for these 3 student from a file named students.txt. (Assume the file contains data in the format: Roll Name Marks). 5 * Implement a recursive function float calculateTotal(struct Student arr[], int n) to calculate the sum of marks of all students in the array. 6 * Display each student's details and the total marks calculated by the recursive function. 7 */ 8 9 #include<stdio.h> 10 #include<stdlib.h> 11 #include<string.h> 12 13 #define FILENAME "students.txt" 14 15 typedef struct Student { 16 int roll; 17 char name[20]; 18 float marks; 19 } Stu; 20 21 void printDetails(Stu *, int); 22 float calculateTotal(struct Student [], int); 23 24 int main() { 25 FILE *input = NULL; 26 Stu stu[3]; 27 int i = 0; 28 29 input = fopen(FILENAME, "r"); 30 if(input == NULL) { 31 printf("\nError opening file %s. Please try again.", FILENAME); 32 exit(1); 33 } 34 35 while(i < 3 && (fscanf(input, "%d %s %f", &stu[i].roll, &stu[i].name, &stu[i].marks) == 3)) i++; 36 printDetails(stu, 3); 37 printf("\n\nTotal Marks: %g", calculateTotal(stu, 3)); 38 fclose(input); 39 return 0; 40 } 41 42 float calculateTotal(struct Student stu[], int n) { 43 if(n <= 0) { 44 return 0; 45 } 46 return stu[n - 1].marks + calculateTotal(stu, n-1); 47 } 48 49 void printDetails(Stu *stu, int n) { 50 int i; 51 printf("\n== Student Details =="); 52 for(i = 0; i < n; i++) { 53 printf("\nStudent Roll: %d" 54 "\nStudent Name: %s" 55 "\nStudent Marks: %g\n", 56 stu[i].roll, stu[i].name, stu[i].marks); 57 } 58 }