المصفوفات(array) في لغة ++C: حلول مبتكرة لأسئلة متنوعة

codinglabsolution

 Ex1: Write a C++ program, using function, to find if the array's elements are in order or not.

Sol//

برنامج C++ يستخدم دالة للتحقق مما إذا كانت المصفوفة في ترتيب تصاعدي:

#include <iostream>

using namespace std;

bool isAscendingOrder(const int arr[], int n) {
  """Checks if an array is in ascending order.

  Args:
      arr: The input array.
      n: The size of the array.

  Returns:
      True if the array is in ascending order, False otherwise.
  """

  for (int i = 0; i < n - 1; i++) {
    if (arr[i] > arr[i + 1]) {
      return false;
    }
  }
  return true;
}

int main() {
  int arr[] = {1, 3, 5, 7, 9}; // Replace with your test array
  int n = sizeof(arr) / sizeof(arr[0]);

  if (isAscendingOrder(arr, n)) {
    cout << "The array is in ascending order." << endl;
  } else {
    cout << "The array is not in ascending order." << endl;
  }

  return 0;
}


Ex2: Write a C++ program, using function, to compute the number of zeros in the array.

Sol//

برنامج C++ يستخدم دالة لحساب عدد الأصفار في المصفوفة:

#include <iostream>

using namespace std;

int countZeros(const int arr[], int n) {
  """Counts the number of zeros in an array.

  Args:
      arr: The input array.
      n: The size of the array.

  Returns:
      The number of zeros in the array.
  """

  int count = 0;
  for (int i = 0; i < n; i++) {
    if (arr[i] == 0) {
      count++;
    }
  }
  return count;
}

int main() {
  int arr[] = {0, 0, 1, 2, 0, 3, 4}; // Replace with your test array
  int n = sizeof(arr) / sizeof(arr[0]);

  int numZeros = countZeros(arr, n);

  cout << "The number of zeros in the array is: " << numZeros << endl;

  return 0;
}


Ex3: Write a C++ program, using function, to find the value of array C from add array A and array B.

C[i] = A [i] + B[i];

Sol//

برنامج C++ يستخدم وظائف للعثور على مجموع العناصر المقابلة في صفيفين وتخزين النتيجة في صفيف ثالث:

#include <iostream>

using namespace std;

// Function to add two arrays and store the result in a new array
void addArrays(const int arr1[], const int arr2[], int n, int result[]) {
  """Adds corresponding elements of two arrays and stores the sum in a new array.

  Args:
      arr1: The first input array.
      arr2: The second input array.
      n: The size of the arrays (assumed to be equal).
      result: The array to store the sum (must have enough space).
  """

  for (int i = 0; i < n; i++) {
    result[i] = arr1[i] + arr2[i];
  }
}

int main() {
  int n;

  cout << "Enter the size of the arrays: ";
  cin >> n;

  // Ensure arrays have enough space
  int arr1[n], arr2[n], result[n];

  cout << "Enter elements for array A: ";
  for (int i = 0; i < n; i++) {
    cin >> arr1[i];
  }

  cout << "Enter elements for array B: ";
  for (int i = 0; i < n; i++) {
    cin >> arr2[i];
  }

  addArrays(arr1, arr2, n, result);

  cout << "Array C (A + B): ";
  for (int i = 0; i < n; i++) {
    cout << result[i] << " ";
  }
  cout << endl;

  return 0;
}


Ex4: Write a C++ program, using function, to multiply the array elements by 2.

A[i]= A [i]*2;

Sol//

برنامج C++ يستخدم دالة لضرب كل عنصر في المصفوفة بـ 2:

#include <iostream>

using namespace std;

// Function to multiply array elements by 2
void multiplyByTwo(int arr[], int n) {
  """Multiplies each element of an array by 2 and modifies the original array.

  Args:
      arr: The input array.
      n: The size of the array.
  """

  for (int i = 0; i < n; i++) {
    arr[i] *= 2; // In-place modification
  }
}

int main() {
  int arr[] = {1, 2, 3, 4}; // Replace with your test array
  int n = sizeof(arr) / sizeof(arr[0]);

  cout << "Original array: ";
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;

  multiplyByTwo(arr, n);

  cout << "Array after multiplying by 2: ";
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;

  return 0;
}


Ex5: Write a C++ program, using function, to reads temperatures over the 30 days and calculate the average of them.

Sol//

برنامج C++ يستخدم وظائف لقراءة درجات الحرارة على مدار 30 يومًا وحساب المتوسط:

#include <iostream>

using namespace std;

const int numDays = 30; // Assuming 30 days

// Function to read temperatures
void readTemperatures(float temperatures[]) {
  

  for (int i = 0; i < numDays; i++) {
    cout << "Enter temperature for day " << i + 1 << ": ";
    cin >> temperatures[i];
  }
}

// Function to calculate the average temperature
float calculateAverageTemperature(const float temperatures[]) {
  

  float sum = 0.0f;
  for (int i = 0; i < numDays; i++) {
    sum += temperatures[i];
  }
  return sum / numDays;
}

int main() {
  float temperatures[numDays];

  readTemperatures(temperatures);

  float averageTemp = calculateAverageTemperature(temperatures);

  cout << "Average temperature over 30 days: " << averageTemp << " degrees Celsius" << endl;

  return 0;
}


Ex6: Write a C++ program, using function, to merge two arrays in one array.

Sol//

برنامج C++ يستخدم وظائف لدمج صفيفين في صفيف ثالث:

#include <iostream>

using namespace std;

// Function to merge two arrays into a third array
void mergeArrays(const int arr1[], const int arr2[], int n1, int n2, int merged[]) {
  """Merges two arrays into a new array, assuming enough space in the merged array.

  Args:
      arr1: The first input array (constant to prevent modification).
      arr2: The second input array (constant to prevent modification).
      n1: The size of the first array.
      n2: The size of the second array.
      merged: The array to store the merged elements (must have enough space to hold n1 + n2 elements).
  """

  int i = 0, j = 0, k = 0;
  while (i < n1 && j < n2) {
    // Copy smaller element from either array to the merged array
    if (arr1[i] <= arr2[j]) {
      merged[k++] = arr1[i++];
    } else {
      merged[k++] = arr2[j++];
    }
  }

  // Copy remaining elements from the non-empty array (if any)
  while (i < n1) {
    merged[k++] = arr1[i++];
  }
  while (j < n2) {
    merged[k++] = arr2[j++];
  }
}

int main() {
  int n1, n2;

  cout << "Enter the size of the first array: ";
  cin >> n1;

  cout << "Enter the size of the second array: ";
  cin >> n2;

  int arr1[n1], arr2[n2];
  int merged[n1 + n2]; // Ensure enough space in the merged array

  cout << "Enter elements for the first array: ";
  for (int i = 0; i < n1; i++) {
    cin >> arr1[i];
  }

  cout << "Enter elements for the second array: ";
  for (int i = 0; i < n2; i++) {
    cin >> arr2[i];
  }

  mergeArrays(arr1, arr2, n1, n2, merged);

  cout << "Merged array: ";
  for (int i = 0; i < n1 + n2; i++) {
    cout << merged[i] << " ";
  }
  cout << endl;

  return 0;
}


Ex7: Write C++ program, to read 3*4 2D-array, then find the summation of each col.

Sol//

برنامج C++ لقراءة مصفوفة 3x4 ثنائية الأبعاد، والعثور على مجموع كل عمود، وطباعة النتائج:

#include <iostream>

using namespace std;

int main() {
  const int rows = 3;  // Number of rows in the 2D array
  const int cols = 4;  // Number of columns in the 2D array

  int arr[rows][cols];

  // Read elements for the 2D array
  cout << "Enter elements for the 3x4 array:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cin >> arr[i][j];
    }
  }

  // Calculate and print the sum of each column
  cout << "\nSum of each column:\n";
  for (int j = 0; j < cols; j++) {
    int sum = 0;
    for (int i = 0; i < rows; i++) {
      sum += arr[i][j];
    }
    cout << "Column " << j + 1 << " sum: " << sum << endl;
  }

  return 0;
}


Ex8: Write C++ program, to replace each element in the second diameter (diagonal) with zero.

Sol//

برنامج C++ لاستبدال العناصر في القطر الثاني (القطري المضاد) لمصفوفة ثنائية الأبعاد بصفر:

#include <iostream>

using namespace std;

void replaceSecondDiagonalWithZero(int arr[][MAX_COLS], int rows, int cols) {
  """Replaces elements in the second diagonal (anti-diagonal) with zero.

  Args:
      arr: The 2D array to modify.
      rows: The number of rows in the array.
      cols: The number of columns in the array (assumed to be square).
  """

  // Handle cases where the array is not square
  if (rows != cols) {
    cout << "Error: Array must be square for this operation." << endl;
    return;
  }

  // Iterate through elements on the second diagonal (anti-diagonal)
  for (int i = 0; i < rows; i++) {
    int j = cols - 1 - i;  // Calculate anti-diagonal index (cols - 1 - i)
    if (i != j) {  // Exclude the main diagonal (where i == j)
      arr[i][j] = 0;
    }
  }
}

int main() {
  const int MAX_ROWS = 10;  // Maximum allowed size for the array (adjust as needed)
  const int MAX_COLS = MAX_ROWS; // Assuming a square matrix

  int rows, cols;

  cout << "Enter the dimensions of the square matrix (rows and columns): ";
  cin >> rows >> cols;

  if (rows > MAX_ROWS || cols > MAX_COLS) {
    cout << "Error: Array size exceeds maximum allowed size." << endl;
    return 1;
  }

  int arr[MAX_ROWS][MAX_COLS];

  cout << "Enter elements for the " << rows << "x" << cols << " matrix:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cin >> arr[i][j];
    }
  }

  replaceSecondDiagonalWithZero(arr, rows, cols);

  cout << "\nMatrix with second diagonal replaced by zeros:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cout << arr[i][j] << " ";
    }
    cout << endl;
  }

  return 0;
}


Ex9: Write C++ program, to replace the elements of the main diameter with the elements of the second diameter.

Sol//

برنامج C++ لاستبدال عناصر القطر الرئيسي بعناصر القطر الثاني (القطري المضاد) في مصفوفة مربعة:

#include <iostream>

using namespace std;

void swapMainAndSecondDiagonals(int arr[][MAX_COLS], int rows, int cols) {
  """Swaps the elements of the main diagonal with the elements of the second diagonal (anti-diagonal).

  Args:
      arr: The 2D array to modify (passed by reference).
      rows: The number of rows in the array (assumed to be square).
      cols: The number of columns in the array (assumed to be square).
  """

  // Handle cases where the array is not square
  if (rows != cols) {
    cout << "Error: Array must be square for this operation." << endl;
    return;
  }

  // Iterate through elements on both diagonals (main and anti-diagonal)
  for (int i = 0; i < rows; i++) {
    int mainDiagIndex = i;  // Index for main diagonal (i, i)
    int antiDiagIndex = cols - 1 - i;  // Index for anti-diagonal (i, cols - 1 - i)
    swap(arr[mainDiagIndex][mainDiagIndex], arr[i][antiDiagIndex]);
  }
}

int main() {
  const int MAX_ROWS = 10;  // Maximum allowed size for the array (adjust as needed)
  const int MAX_COLS = MAX_ROWS; // Assuming a square matrix

  int rows, cols;

  cout << "Enter the dimensions of the square matrix (rows and columns): ";
  cin >> rows >> cols;

  if (rows > MAX_ROWS || cols > MAX_COLS) {
    cout << "Error: Array size exceeds maximum allowed size." << endl;
    return 1;
  }

  int arr[MAX_ROWS][MAX_COLS];

  cout << "Enter elements for the " << rows << "x" << cols << " matrix:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cin >> arr[i][j];
    }
  }

  swapMainAndSecondDiagonals(arr, rows, cols);

  cout << "\nMatrix with main and second diagonals swapped:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cout << arr[i][j] << " ";
    }
    cout << endl;
  }

  return 0;
}


Ex10: Write C++ program, to find the summation of odd numbers in 2D-array.

Sol//

برنامج C++ للعثور على مجموع الأعداد الفردية في مصفوفة ثنائية الأبعاد:

#include <iostream>

using namespace std;

int findSumOfOddNumbers(const int arr[][MAX_COLS], int rows, int cols) {
  """Calculates the sum of all odd numbers in the 2D array.

  Args:
      arr: The 2D array to search (assumed to be integer type).
      rows: The number of rows in the array.
      cols: The number of columns in the array.

  Returns:
      The sum of all odd numbers in the array.
  """

  int sum = 0;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      if (arr[i][j] % 2 != 0) {  // Check if element is odd (remainder is not 0)
        sum += arr[i][j];
      }
    }
  }
  return sum;
}

int main() {
  const int MAX_ROWS = 10;  // Maximum allowed size for the array (adjust as needed)
  const int MAX_COLS = MAX_ROWS;

  int rows, cols;

  cout << "Enter the dimensions of the 2D array (rows and columns): ";
  cin >> rows >> cols;

  if (rows > MAX_ROWS || cols > MAX_COLS) {
    cout << "Error: Array size exceeds maximum allowed size." << endl;
    return 1;
  }

  int arr[MAX_ROWS][MAX_COLS];

  cout << "Enter elements for the " << rows << "x" << cols << " array:\n";
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      cin >> arr[i][j];
    }
  }

  int sumOfOdds = findSumOfOddNumbers(arr, rows, cols);

  cout << "\nSum of all odd numbers in the array: " << sumOfOdds << endl;