commit cf5ff5f67efa088e9fa7f206cb371275ad8a1601
parent 147de9a0c20759d3b0c2f30c23b2dbbd8237f6c9
Author: Amit Dutta <amitdutta4255@gmail.com>
Date: Mon, 30 Mar 2026 17:47:06 +0530
Correct recursive total calculation and file handling
Fixed the recursive function to handle base case correctly and added fclose for the file.
Diffstat:
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/Semester_1/practice-c/pc014.c b/Semester_1/practice-c/pc014.c
@@ -41,14 +41,15 @@ int main() {
while(i < 3 && (fscanf(input, "%d %s %f", &stu[i].roll, &stu[i].name, &stu[i].marks) == 3)) i++;
printDetails(stu, 3);
printf("\n\nTotal Marks: %g", calculateTotal(stu, 3));
+ fclose(input);
+ return 0;
}
float calculateTotal(struct Student stu[], int n) {
- if(n == 0) {
- return stu[n].marks;
+ if(n <= 0) {
+ return 0;
}
- float total = stu[n].marks;
- return total + calculateTotal(stu, n-1);
+ return stu[n - 1].marks + calculateTotal(stu, n-1);
}
void printDetails(Stu *stu, int n) {
@@ -60,4 +61,4 @@ void printDetails(Stu *stu, int n) {
"\nStudent Marks: %g\n",
stu[i].roll, stu[i].name, stu[i].marks);
}
-}-
\ No newline at end of file
+}