Array Out of Bounds in C (6 Subjects, 7th Marks Entered)
C
Easy
10 views
Problem Description
Suppose a student has entered the marks for their six subjects into an array. What will happen if they accidentally enter the marks for a seventh subject as well? Will the program crash, or something else? How can we handle this situation?
Official Solution
#include <stdio.h>
int main() {
int marks[6];
int i;
int total = 0;
printf("Enter marks of 6 subjects only:n");
for (i = 0; i < 6; i++) {
printf("Subject %d marks: ", i + 1);
scanf("%d", &marks[i]);
// optional validation
if (marks[i] < 0 || marks[i] > 100) {
printf("Invalid marks! Enter marks between 0 and 100.n");
i--; // re-enter same subject marks
}
}
for (i = 0; i < 6; i++) {
total += marks[i];
}
printf("nTotal Marks = %dn", total);
printf("Average Marks = %.2fn", total / 6.0);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!