Untitled

 avatar
ketronix
c_cpp
2 years ago
1.9 kB
6
Indexable
#include <iostream>
#include <malloc.h>

using namespace std;

int sumBetweenNegatives(float arr[], int size) {
    int firstNegativeIndex = -1;
    int secondNegativeIndex = -1;
    int sum = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] < 0) {
            if (firstNegativeIndex == -1) {
                firstNegativeIndex = i;
            } else if (secondNegativeIndex == -1) {
                secondNegativeIndex = i;
                break;
            }
        }
    }

    if (firstNegativeIndex != -1 && secondNegativeIndex != -1) {
        for (int i = firstNegativeIndex + 1; i < secondNegativeIndex; i++) {
            sum += arr[i];
        }
    }

    return sum;
}

void reorder(float arr[], int n)
{
    int i = -1, temp = 0;
    for (int j = 0; j < n; j++) {
        if (abs(arr[j]) <= 1) {
            i++;
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}

int countElements(float* arr) {
    int count = 0;
    while(*arr++) // incrementing the pointer to get the size of dynamic array
    {
        count++;
    }
    return count;
}

int main() {

    float* array = new float[] { -1, 1, 2, -0.5, 4, 5, 7};
    int count = countElements(array);
    cout << "Elements in array: " << "7" << endl;

    cout << "Array: ";
    for (int i = 0; i < count; i++)
        cout << array[i] << " ";
    cout << endl;

    float min = array[0];
    float min_index = 0;
    for (int i = 0; i <= count; ++i) {
        if (min > array[i])
        {
            min = array[i];
            min_index = i;
        }
    }

    auto sum = sumBetweenNegatives(array, count);
    reorder(array, 7);

    cout << "Sum of positive numbers: " << sum << endl;
    cout << "Minimal element in array: " << min << " Index: " << min_index << endl;

    cout << "New Array: ";
    for (int i = 0; i < count; i++)
        cout << array[i] << " ";
    return 0;
}
Editor is loading...