#include <iostream>
using namespace std;
// Function to initialize the 2D array
void initializeArray(int arr[][3], int rows, int cols) {
cout << "Enter elements of the 2D array:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << "Enter element at position [" << i << "][" << j << "]: ";
cin >> arr[i][j];
}
}
}
// Function to display the 2D array
void displayArray(int arr[][3], int rows, int cols) {
cout << "2D Array elements:" << endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
cout << arr[i][j] << "\t";
}
cout << endl;
}
}
// Function to calculate the sum of the 2D array
int calculateSum(int arr[][3], int rows, int cols) {
int sum = 0;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
sum += arr[i][j];
}
}
return sum;
}
// Function to calculate the average of the 2D array
double calculateAverage(int arr[][3], int rows, int cols) {
int sum = calculateSum(arr, rows, cols);
return static_cast<double>(sum) / (rows * cols);
}
int main() {
const int rows = 3;
const int cols = 3;
int myArray[rows][cols];
// Initialize the array
initializeArray(myArray, rows, cols);
// Display the array
displayArray(myArray, rows, cols);
// Calculate and display the sum
int sum = calculateSum(myArray, rows, cols);
cout << "Sum of the array: " << sum << endl;
// Calculate and display the average
double average = calculateAverage(myArray, rows, cols);
cout << "Average of the array: " << average << endl;
return 0;
}
____________________________________
#include <iostream>
using namespace std;
int main()
{
int *arr;
int s;
cout<<"Enter Array Size: ";
cin>>s;//5
//dynamic memory allocation
arr = new int[s];
for(int i =0; i<s; i++)
{
cout<<"Enter array elements for arr["<<i<<"]: ";
cin>>arr[i];
}
for(int i =0; i<s; i++)
{
cout<<"arr["<<i<<"]: "<<arr[i]<<endl;
}
//deallocation
delete[] arr;
return 0;
}