Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking if an array has a negative and duplicate numbers in it

I’m trying to check to see how many negative numbers in an arrays and check if there’s any duplicate numbers in the same array.

Here’s the code that I’m using:

#include<stdio.h>

int main()
{
int n = 0;
int negative_count = 0;
int duplicate_count = 0;
// input lenght of the array
scanf("%d", &n);
getchar();
int arr[n];
for(int i = 0;i < n;i++){
    //input elements of the array
    scanf("%d", &arr[i]);
    getchar();
}

int len = sizeof(arr) / sizeof(arr[0]);

for(int i=0;i<len;i++){
    if(arr[i] < 0){
        negative_count++;
    }
    for(int j= i+1;j<len;j++){
        if(arr[i] == arr[j]){
            duplicate_count++;
        }
    }
}

printf("Number of negative numbers: %d\n", negative_count);
printf("Number of duplicates: %d", duplicate_count);

return 0;
}

Input

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

5
1 -1 2 3 -3

output

Number of negative numbers: 2
Number of duplicates: 0

the output for the negative number is correct, but the output for the duplicate is not what I wanted. It should’ve output 2 because 1 and -1 boht have the number one, and so does 3 and -3. How should I go about this?

>Solution :

If you actually want 1 and -1 to count as the same number you should use the abs() function to use the absolute value when searching for "duplicates".

abs(-1) = 1
abs(1) = 1


-1 == 1               returns false
abs(-1) == abs(1)     returns true

also remember to include <stdlib.h> to use abs()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading