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;
return 0;
}
Ex11: Write C++ program, to find (search) X value in 2D-array, and return the index of it's location.
Sol//
برنامج C++ للبحث عن القيمة (X) في مصفوفة ثنائية الأبعاد وإرجاع موقعها (المؤشرات) إذا وجدت:
#include <iostream>
#include <limits> // For numeric_limits<int>::max()
using namespace std;
struct Index {
int row;
int col;
};
Index findValueIn2DArray(const int arr[][MAX_COLS], int rows, int cols, int value) {
"""Searches for a value (X) in the 2D array and returns the index of its location.
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.
value: The value to search for.
Returns:
An Index struct containing the row and column indices if found, or {-1, -1} if not found.
"""
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (arr[i][j] == value) {
return {i, j}; // Return Index struct with row and column
}
}
}
// Value not found
return {-1, -1};
}
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, value;
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];
}
}
cout << "Enter the value to search for (X): ";
cin >> value;
Index foundIndex = findValueIn2DArray(arr, rows, cols, value);
if (foundIndex.row == -1 && foundIndex.col == -1) {
cout << "Value " << value << " not found in the array." << endl;
} else {
cout << "Value " << value << " found at index (" << foundIndex.row << ", "
<< foundIndex.col << ")" << endl;
}
return 0;
}
Ex12: Write C++ program, to convert 1D-array that size [16] to 2D-array that size of [4] [4].
Sol//
برنامج C++ لتحويل مصفوفة 1D بحجم 16 إلى مصفوفة ثنائية الأبعاد بحجم 4x4:
#include <iostream>
using namespace std;
int main() {
const int oneDArraySize = 16;
const int rows = 4;
const int cols = 4;
if (oneDArraySize != rows * cols) {
cout << "Error: 1D array size must be equal to the product of 2D array dimensions." << endl;
return 1;
}
int oneDArray[oneDArraySize];
int twoDArray[rows][cols];
// Get elements for the 1D array
cout << "Enter elements for the 1D array (size " << oneDArraySize << "):\n";
for (int i = 0; i < oneDArraySize; i++) {
cin >> oneDArray[i];
}
// Convert 1D array to 2D array
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
twoDArray[i][j] = oneDArray[index++];
}
}
// Print the resulting 2D array
cout << "\nConverted 2D array (size " << rows << "x" << cols << "):\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << twoDArray[i][j] << " ";
}
cout << endl;
}
return 0;
}
Ex13: Write C++ program, to read A[ n, n ] of character, then find array B and array C, such that B contain only capital letters and C contain only small letters.
Sol//
برنامج C++ لقراءة مصفوفة الأحرف A[n, n] وإنشاء مصفوفتين منفصلتين B وC لتخزين الأحرف الكبيرة والصغيرة، على التوالي:
#include <iostream>
#include <cctype> // For tolower and toupper
using namespace std;
int main() {
int n;
cout << "Enter the size of the square character array (n x n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
char A[n][n];
char B[n * n]; // Allocate enough space to hold all characters (worst case)
char C[n * n];
int bIndex = 0; // Index for array B (capital letters)
int cIndex = 0; // Index for array C (small letters)
// Read elements for the 2D character array
cout << "Enter characters for the " << n << "x" << n << " array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
// Separate capital and small letters
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
char ch = A[i][j];
if (isupper(ch)) { // Check if uppercase letter
B[bIndex++] = ch;
} else if (islower(ch)) { // Check if lowercase letter
C[cIndex++] = ch;
}
// Ignore non-alphabetic characters
}
}
// Adjust array sizes based on actual number of elements
int actualBSize = bIndex;
int actualCSize = cIndex;
B[actualBSize] = '\0'; // Null terminate array B (optional)
C[actualCSize] = '\0'; // Null terminate array C (optional)
// Print the resulting arrays B and C
cout << "\nArray B (capital letters):\n";
for (int i = 0; i < actualBSize; i++) {
cout << B[i] << " ";
}
cout << "\n\nArray C (small letters):\n";
for (int i = 0; i < actualCSize; i++) {
cout << C[i] << " ";
}
cout << endl;
return 0;
}
Ex14: Write C++ program, to read A[ n, n ] of numbers, then put 10 instead each even positive number.
Sol//
برنامج C++ لقراءة مصفوفة الأرقام A[n, n]، واستبدال الأرقام الموجبة بـ 10، وتخزين النتيجة مرة أخرى في A:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the size of the square number array (n x n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
int A[n][n];
// Read elements for the 2D array
cout << "Enter elements for the " << n << "x" << n << " array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
// Modify elements (replace even positive numbers with 10)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (A[i][j] > 0 && A[i][j] % 2 == 0) { // Check for positive and even
A[i][j] = 10;
}
}
}
// Print the modified array
cout << "\nModified array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
Ex15: Write C++ program, to read A[ n, n ] of numbers, then put 10 instead each even positive number in the first diagonal.
Sol//
برنامج C++ لقراءة مصفوفة الأرقام A[n, n]، واستبدال الأرقام الموجبة بـ 10 في القطر الأول (القطري الرئيسي)، وتخزين النتيجة مرة أخرى في A:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the size of the square number array (n x n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
int A[n][n];
// Read elements for the 2D array
cout << "Enter elements for the " << n << "x" << n << " array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
// Modify elements (replace even positive numbers in the first diagonal)
for (int i = 0; i < n; i++) {
if (A[i][i] > 0 && A[i][i] % 2 == 0) { // Check for positive and even on main diagonal
A[i][i] = 10;
}
}
// Print the modified array
cout << "\nModified array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
Ex16: Write C++ program, to read A[ n, n ] of numbers, then find the minimum number in array.
Sol//
برنامج C++ لقراءة مصفوفة أرقام A[n, n] والعثور على الحد الأدنى للعدد في المصفوفة بأكملها:
#include <iostream>
#include <limits> // For numeric_limits<int>::max()
using namespace std;
int main() {
int n;
cout << "Enter the size of the square number array (n x n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
int A[n][n];
int minNumber = numeric_limits<int>::max(); // Initialize with maximum integer value
// Read elements for the 2D array
cout << "Enter elements for the " << n << "x" << n << " array:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
// Update minimum number if current element is smaller
if (A[i][j] < minNumber) {
minNumber = A[i][j];
}
}
}
// Print the minimum number
cout << "\nMinimum number in the array: " << minNumber << endl;
return 0;
}
Ex17: Write C++ program, to exchange row1 and row3 in 4*3 array.
Sol//
برنامج C++ لتبادل الصف 1 والصف 3 في مصفوفة 4x3:
#include <iostream>
using namespace std;
int main() {
const int rows = 4;
const int cols = 3;
int A[rows][cols];
// Read elements for the 4x3 array
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 >> A[i][j];
}
}
// Swap row 1 and row 3 (assuming 0-based indexing)
for (int j = 0; j < cols; j++) {
swap(A[0][j], A[2][j]);
}
// Print the modified array
cout << "\nArray after exchanging row 1 and row 3:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
Ex18: Write C++ program, to exchange row0 with col3 in 4*4 array.
Sol//
برنامج C++ لتبادل الصف 0 مع العمود 3 في مصفوفة 4x4:
#include <iostream>
using namespace std;
int main() {
const int rows = 4;
const int cols = 4;
int A[rows][cols];
// Read elements for the 4x4 array
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 >> A[i][j];
}
}
// Swap row 0 with column 3 (assuming 0-based indexing)
for (int i = 0; i < rows; i++) {
swap(A[i][0], A[i][3]);
}
// Print the modified array
cout << "\nArray after exchanging row 0 and column 3:\n";
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
Ex19: Write C++ program, to find the greatest number in the second diagonal, in 3*3 array.
Sol//
#include <iostream>
using namespace std;
int main() {
const int size = 3; // Assuming a 3x3 array
int A[size][size];
int greatestInSecondDiagonal = numeric_limits<int>::min(); // Initialize with minimum integer value
// Read elements for the 3x3 array
cout << "Enter elements for the 3x3 array:\n";
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cin >> A[i][j];
}
}
// Find the greatest number in the second diagonal
for (int i = 0; i < size; i++) {
// Check if element is within the second diagonal (avoiding out-of-range access)
if (i < size - 1 - i) {
greatestInSecondDiagonal = max(greatestInSecondDiagonal, A[i][size - 1 - i]);
}
}
// Print the result
if (greatestInSecondDiagonal == numeric_limits<int>::min()) {
cout << "No elements found on the second diagonal." << endl;
} else {
cout << "Greatest number in the second diagonal: " << greatestInSecondDiagonal << endl;
}
return 0;
}
Ex20: Write C++ program, to read X[ n ], and rotate the elements to the left by one position.
Sol//
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the size of the array (n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
int X[n];
// Read elements for the array
cout << "Enter elements for the array:\n";
for (int i = 0; i < n; i++) {
cin >> X[i];
}
// Store the first element
int temp = X[0];
// Shift elements to the left by one position
for (int i = 0; i < n - 1; i++) {
X[i] = X[i + 1];
}
// Store the shifted first element at the end
X[n - 1] = temp;
// Print the rotated array
cout << "\nArray after rotating left by one position:\n";
for (int i = 0; i < n; i++) {
cout << X[i] << " ";
}
cout << endl;
return 0;
}
Ex21: Write C++ program, to read A[ n ] and a location Z then delete the number at location Z from the array, and print the new array after deletion.
Sol//
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the size of the array (n): ";
cin >> n;
if (n <= 0) {
cout << "Error: Array size must be positive." << endl;
return 1;
}
int A[n];
// Read elements for the array
cout << "Enter elements for the array:\n";
for (int i = 0; i < n; i++) {
cin >> A[i];
}
int Z;
cout << "Enter the location (Z) from which to delete the element (0 to " << n - 1 << "): ";
cin >> Z;
// Check for valid location Z (within array bounds)
if (Z < 0 || Z >= n) {
cout << "Error: Invalid location Z. Must be within 0 to " << n - 1 << endl;
return 1;
}
// Shift elements to the left to overwrite the deleted element
for (int i = Z; i < n - 1; i++) {
A[i] = A[i + 1];
}
// Reduce the array size logically (optional, not strictly necessary for printing)
n--;
// Print the array after deletion
cout << "\nArray after deleting element at location " << Z << ":\n";
for (int i = 0; i < n; i++) {
cout << A[i] << " ";
}
cout << endl;
return 0;
}