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

Time:11-12

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

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?

CodePudding user response:

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()

CodePudding user response:

I fixed my code and it works, just need to use the abs() function for comparing the array. And I also got rid of some unnecesarry code.

Here's the new code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
int n = 0;
int negative_count = 0;
int duplicate_count = 0;

// input length of the array
scanf("%d", &n);
int arr[n];

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

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

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

return 0;
}
  • Related