Many functions regarding arrays

PHOTO EMBED

Fri Dec 06 2024 12:13:48 GMT+0000 (Coordinated Universal Time)

Saved by @khadizasultana #loop #array #c++

// Khadiza Sultana
#include<iostream>
#include <climits>
using namespace std;
int sum(int arr[], int size){
    int sum = 0;
    for(int i = 0; i < size; i++){
        sum += arr[i];
    }
    return sum;
}
int product(int arr[], int size){
    int product = 1;
    for(int i = 0; i < size; i++){
        product *= arr[i];
    }
    return product;
}
void swap(int &a, int &b){
    a = a + b;
    b = a - b;
    a = a - b;
}
void uniqueElement(int arr[], int size){
    for(int i = 0; i < size; i++){
        bool isUnique = true;
        for(int j = 0; j < size; j++){
            if(i != j && arr[i] == arr[j]){
                isUnique = false;
                break;
            }
        }
        if(isUnique) cout << arr[i] << " ";
    }
    cout << endl;
} 
void reverseMinAndMax(int arr[], int size){
    int largest = INT_MIN, smallest = INT_MAX, largest_index = -1, smallest_index = -1;
    for(int i = 0; i < size; i++){
        if(arr[i] > largest){
            largest = arr[i];
            largest_index = i;
        }
        if(arr[i] < smallest){
            smallest = arr[i];
            smallest_index = i;
        }
    }
    swap(arr[largest_index], arr[smallest_index]);
    for(int i = 0; i < size; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
}
void intersection(int arr1[], int size1, int arr2[], int size2){
    for(int i = 0; i < size1; i++){
        bool repeated = false;
        for(int j = 0; j < size1; j++){
            if(i != j && arr1[i] == arr1[j]){
               repeated = true;
               break;
            }
        }
        if(repeated) arr1[i] = INT_MAX;
        for(int j = 0; j < size2; j++){
            if(arr1[i] == arr2[j]){
               cout << arr1[i] << " ";
               break;
            }
        }

    }
    cout << endl;
}
int main(){
    int arr1[] = {1, 2, 4, 6, 4, 6, 2, 5, 9};
    int size1 = sizeof(arr1) / sizeof(int);
    int arr2[] = {2, 4, 3, 5, 8, 6, 3};
    int size2 = sizeof(arr2) / sizeof(int);
    cout << "Sum of elements : " << sum(arr1, size1) << endl;
    cout << "Product of elements : " << product(arr1, size1) << endl;
    cout << "The elements of the first array after the maximum element and minimum element are reversed : ";
    reverseMinAndMax(arr1, size1);
    cout << "The unique elements in the first array : ";
    uniqueElement(arr1, size1);
    cout << "The intersecting elements between the first and second array : ";
    intersection(arr1, size1, arr2, size2);
    return 0;
}
content_copyCOPY