Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
1
Indexable
Never
#include <iostream>
#include <fstream>
using namespace std;

// Function to create an array in ascending order
void createAscendingArray(int a[], int na) {
    for (int i = 0; i < na; i++) {
        a[i] = i + 1;
    }
}

// Function to create an array in descending order
void createDescendingArray(int b[], int nb) {
    int value = nb;
    for (int i = 0; i < nb; i++) {
        b[i] = value;
        value--;
    }
}

// Function to find common elements and write them to a file
void findCommonElements(int a[], int na, int b[], int nb) {
    ofstream outputFile("comune.out");
    int i = 0, j = 0;
    bool commonElementsExist = false;

    while (i < na && j < nb) {
        if (a[i] == b[j]) {
            outputFile << a[i] << " ";
            i++;
            j++;
            commonElementsExist = true;
        } else if (a[i] < b[j]) {
            i++;
        } else {
            j++;
        }
    }

    if (!commonElementsExist) {
        outputFile << "nu exista";
    }

    outputFile.close();
}

int main() {
    int na, nb;

    // Read the number of elements for array a and b
    cout << "Enter the number of elements for array a: ";
    cin >> na;
    cout << "Enter the number of elements for array b: ";
    cin >> nb;

    int* a = new int[na];
    int* b = new int[nb];

    // Create arrays a and b
    createAscendingArray(a, na);
    createDescendingArray(b, nb);

    // Find and write common elements to the file
    findCommonElements(a, na, b, nb);

    // Clean up memory
    delete[] a;
    delete[] b;

    cout << "Common elements have been written to comune.out file." << endl;

    return 0;
}