Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find marks of students for boys or girls
In C programming, we can solve problems involving array processing based on index patterns. This program calculates the sum of marks for either boys or girls, where boys' marks are stored at even indices (0, 2, 4, ...) and girls' marks are stored at odd indices (1, 3, 5, ...).
Syntax
int calculateMarks(int marks[], int n, char gender);
Algorithm
To solve this problem, we follow these steps −
- Initialize
g_sumandb_sumto 0 - Iterate through the array from index 0 to n-1
- If index is odd, add marks to
g_sum(girls) - If index is even, add marks to
b_sum(boys) - Return the appropriate sum based on gender input
Example
Let us see the implementation to calculate marks based on gender −
#include <stdio.h>
int solve(int marks[], int n, char gender) {
int g_sum = 0; // Girls' marks sum
int b_sum = 0; // Boys' marks sum
for(int i = 0; i < n; i++) {
if(i % 2 != 0) {
g_sum += marks[i]; // Odd indices for girls
} else {
b_sum += marks[i]; // Even indices for boys
}
}
if(gender == 'b')
return b_sum;
return g_sum;
}
int main() {
int marks[] = {8, 5, 2, 6, 7, 5, 9, 9, 7};
int n = 9;
char gender = 'g';
printf("Marks array: ");
for(int i = 0; i < n; i++) {
printf("%d ", marks[i]);
}
printf("\nGender: %c<br>", gender);
int sum = solve(marks, n, gender);
printf("Sum of marks: %d<br>", sum);
return 0;
}
Marks array: 8 5 2 6 7 5 9 9 7 Gender: g Sum of marks: 25
How It Works
In the given example with marks = [8,5,2,6,7,5,9,9,7] and gender = 'g':
- Boys' marks (even indices): marks[0]=8, marks[2]=2, marks[4]=7, marks[6]=9, marks[8]=7. Sum = 33
- Girls' marks (odd indices): marks[1]=5, marks[3]=6, marks[5]=5, marks[7]=9. Sum = 25
- Since gender is 'g', the function returns 25
Key Points
- Even indices (0, 2, 4, ...) represent boys' marks
- Odd indices (1, 3, 5, ...) represent girls' marks
- The modulo operator (%) determines if an index is even or odd
- Function returns the sum based on the gender parameter ('b' for boys, 'g' for girls)
Conclusion
This program efficiently separates and sums marks based on array index patterns. It demonstrates the use of modulo arithmetic to distinguish between even and odd indices for gender-based mark calculation.
Advertisements
