'Find the lonely integer in an array

Please refer to this hackerrank challenge if you can.

The problem is to find the lonely integer in an array, given an array consists of only pairs except one lonely integer.

The problem is with this test case

9
4 9 95 93 57 4 57 93 9

9 is array size and below is the array

See the part of code highlighted by //------

If I place scanf("%d", &n) above int arr[n], the code works fine, but it gives horrible results the other way round.

#include <stdio.h>

int lonely_integer(int* a, int size);

int main(){
    //n is size of array, i is counter variable
    int n, i, result;
    // ---------------------
    int arr[n];
    scanf("%d", &n);
    // ---------------------
    printf("%d\n", n);
    for(i = 0; i < n; i++){
        scanf("%d", &arr[i]);
    }
    result = lonely_integer(arr, n);
    printf("%d", result);
    return 0;
}


int lonely_integer(int* a, int size){
    int i;
    int res = 0;
    for(i = 0; i < size; i++){
        res = res ^ a[i];
    }

    return res;
}


Solution 1:[1]

Range of n is given in the question is 1 <= N < 100 which is small and a variable length array can be used. But you are doing wrong here

int arr[n];   // n is uninitialized. Its value is indeterminate.
scanf("%d", &n);  

You need to initialize n before using it as array size

scanf("%d", &n);
int arr[n];

Solution 2:[2]

Allocating array with a uninitialized variable, will lead to undefined behavior and the compiler will throw a warning "variable used uninitialized in this function"

If you are getting the size of array at runtime, it would be wise to use dynamic memory allocation as @Mints97 posted

int data_size;
int *data_array;
scanf("%d", &data_size);
data_array = (int*)calloc(data_size,sizeof(int));
/*
 .
*/
// Free the memory at the end
free(data_array);
data_array = NULL;

If you want to set size of array at compile time, you can define a macro

#define DATA_SIZE 9

or set the macro while compiling the code

gcc test.c -o test -DDATA_SIZE=9 -Wall

Solution 3:[3]

Value of 'n' has to be defined before it has used.like you are using

int arr[n];

before reading the value of 'n'. So compiler will not know, how many number of elements are present in the array 'n' can be a garbage value.how much amount of memory it should allocate to an array.

hence you gotta read the value of 'n' before using it an array definition.

Solution 4:[4]

function lonelyInteger(a){
 let n = [1,2,3,4,3,2,1];
 let unique = a.filter(function(value){
 return a.indexOf(value) === a.lastindexOf(value)
 })
 retun unique[0]
 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sridhar Nagarajan
Solution 3 Giriraj Pawar
Solution 4 user438383