Array Exercises
- Write a program that takes the number of grades from the user, prints
these grades, and then calculates the sum of the grades.
Answer
#include <iostream>
using namespace std;
int main() {
int n; // number of grades
cout << "Enter the number of grades: ";
cin >> n;
int grades[n]; // array to store the grades
int sum = 0; // variable to store the sum of grades
// Taking grades input from the user
for (int i = 0; i < n; i++) {
cout << "Enter grade " << (i + 1) << ": ";
cin >> grades[i];
sum += grades[i]; // adding each grade to the sum
}
// Printing the grades
cout << "The grades are: ";
for (int i = 0; i < n; i++) {
cout << grades[i] << " ";
}
cout << endl;
// Printing the sum of the grades
cout << "The sum of the grades is: " << sum << endl;
return 0;
}
1
- Write a function named sumArray that receives two parameters:
o an array of element type int
o an int that contains the number of elements of the array.
The function returns the sum of the elements of the array as an int.
After defining the function, write a program that takes the number of elements
from the user, allows the user to input these elements, and then calculates
and displays the sum of elements using SumArray function.
Answer
#include <iostream>
using namespace std;
int sumArray(int array[],int numElements) {
int sum = 0;
for (int i = 0; i < numElements; i++) {
sum += array[i];
}
return sum;
}
int main() {
int numElements;
cout << "Enter the number of elements in the array: ";
cin >> numElements;
int array[numElements];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < numElements; i++) {
cout << "Element " << i + 1 << ": ";
cin >> array[i];
}
int result = sumArray(array, numElements);
cout << "Sum: " << result << endl;
return 0;
}