Week6: Arrays (1D Arrays) in C
Q1. Student Marks, Total, Percentage and Grade
Question:
Write a C program to read marks of 5 subjects of a student, calculate the total, percentage, and assign grade according to the following criteria:
| Percentage | Grade |
|---|---|
| >= 90 | A |
| >= 80 | B |
| >= 70 | C |
| >= 60 | D |
| >= 40 | E |
| < 40 | F |
Program:
#include <stdio.h>
int main() {
int marks[5], total = 0;
float p;
char grade;
for (int i = 0; i < 5; i++) {
printf("\nEnter marks: ");
scanf("%d", &marks[i]);
total += marks[i];
}
p = total / 5.0;
if (p >= 90) grade = 'A';
else if (p >= 80) grade = 'B';
else if (p >= 70) grade = 'C';
else if (p >= 60) grade = 'D';
else if (p >= 40) grade = 'E';
else grade = 'F';
printf("Total: %d\nPercentage: %.2f\nGrade: %c\n", total, p, grade);
return 0;
}
````
---
## Q2. Check if Two Marks Lists Are Identical
**Question:**
Write a C program to read two mark lists of equal size (10 elements each) and check whether they are identical or not.
**Program:**
```c
#include <stdio.h>
int main() {
int marks1[10], marks2[10], identical = 1;
printf("Enter 10 marks for the first list:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &marks1[i]);
}
printf("Enter 10 marks for the second list:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &marks2[i]);
}
for (int i = 0; i < 10; i++) {
if (marks1[i] != marks2[i]) {
identical = 0;
break;
}
}
if (identical) {
printf("The two marks lists are identical.\n");
} else {
printf("The two marks lists are not identical.\n");
}
return 0;
}
Q3. Sum of All Elements in an Array
Question: Write a C program to find the sum of all elements in an integer array.
Program:
#include <stdio.h>
int main() {
int arr[10], sum = 0;
printf("Enter 10 integers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < 10; i++) {
sum += arr[i];
}
printf("The sum of all elements is: %d\n", sum);
return 0;
}
Q4. Sum of Prime Numbers in an Array
Question: Write a C program to find all prime numbers in an array and calculate their sum.
Program:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
int main() {
int n, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < n; i++) {
if (isPrime(arr[i])) {
sum += arr[i];
}
}
printf("Sum of prime numbers: %d\n", sum);
return 0;
}