Here's a C program that calculates the CGPA (Cumulative Grade Point Average) of a student:
#include <stdio.h>
#define MAX_SUBJECTS 10
float calculateCGPA(int credits[], float grades[], int numSubjects) {
int totalCredits = 0;
float weightedSum = 0.0;
for (int i = 0; i < numSubjects; i++) {
totalCredits += credits[i];
weightedSum += credits[i] * grades[i];
}
if (totalCredits == 0) {
return 0.0;
}
return weightedSum / totalCredits;
}
int main() {
int credits[MAX_SUBJECTS];
float grades[MAX_SUBJECTS];
int numSubjects;
printf("Enter the number of subjects: ");
scanf("%d", &numSubjects);
printf("Enter the credits and grades for each subject:\n");
for (int i = 0; i < numSubjects; i++) {
printf("Subject %d: \n", i + 1);
printf(" Credits: ");
scanf("%d", &credits[i]);
printf(" Grade (out of 10): ");
scanf("%f", &grades[i]);
}
float cgpa = calculateCGPA(credits, grades, numSubjects);
printf("CGPA: %.2f\n", cgpa);
return 0;
}
In this program, we define the maximum number of subjects as MAX_SUBJECTS
. We have a function calculateCGPA
that takes arrays of credits and grades, along with the number of subjects, as input and returns the CGPA.
Inside the calculateCGPA
function, we initialize variables totalCredits
and weightedSum
to 0. We then iterate through the arrays of credits and grades, accumulating the total credits and calculating the weighted sum by multiplying the credits with the grades. Finally, we divide the weighted sum by the total credits to obtain the CGPA.
In the main
function, the user is prompted to enter the number of subjects. Then, in a loop, the program asks for the credits and grades for each subject and stores them in the respective arrays. The calculateCGPA
function is called with the arrays and the number of subjects to compute the CGPA. Finally, the calculated CGPA is displayed using the printf
function.
You can compile and run this program, entering the credits and grades for each subject, to calculate the CGPA of a student.