comp_questions
comp_questions

Reputation: 13

Finding the second positive value in an array

I'm trying to create a program that outputs the second positive value in an array of integers. If there is no second positive number, it will output "not positive enough." However, my function doesn't work for some reason. Would someone be able to point out why? Thanks :)

#include <stdio.h>

#define NOT_POSITIVE_ENOUGH 0

int array_second_positive(int size, int array[size]) {
    int second_array[size];

    int i = 0;
    int j = 0;
    while (i < size) {
        if (array[i] > 0) {
            scanf("%d", &second_array[j]);
            j++;
        }
    i++;
    }

    if (j < 2) {
        return 0;
    }
    else {
        return second_array[1];
    }
}

#define MAX_SIZE 100

int main(void) {
    int size1 = 7;
    int array1[MAX_SIZE] = {3, -14, 15, 9, 2, 6, 5};

    int result1 = array_second_positive(size1, array1);
    if (result1 == NOT_POSITIVE_ENOUGH) {
        printf("array1 wasn't positive enough!\n");
    } else {
        printf("The second positive value from array1 is: %d\n", result1);
    }

return 0;
}

Upvotes: 1

Views: 119

Answers (2)

vmt
vmt

Reputation: 860

First of all, scanf("%d", &second_array[j]); probably does not do what you think it does. Refer to (for example): scanf, and consider using: second_array[j] = array[i]; instead.

Though a simpler and more concise approach would be:

int array_second_positive(int size, int *arr) {
    int found = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] > 0) {
            if (found) return arr[i];
            found = 1;
        }
    }
    return 0;
}

Upvotes: 1

anoopknr
anoopknr

Reputation: 3355

The error was simple , please change :-

scanf("%d", &second_array[j]); 

To :

second_array[j] = array[i];

Be careful when you code !

Upvotes: 0

Related Questions