I do not understand what is wrong with this code of Linear search. It compiles but on execution exits without output.
turns - no. of test cases.
size - size of array.
x - element to be searched.
#include <stdio.h>
int linearSearch(int arr[], int size, int element)
{
int i = 0;
for(i=0; i< size; i++)
{
if(arr[i] == element)
{
return i;
}
}
return 0;
}
int main()
{
int turns, size;
scanf("%d", &turns);
while(turns--)
{
scanf("%d", &size);
int arr[size];
for(int j=0; j < size; j++)
{
scanf("%d", arr[j]);
}
int x;
scanf("%d", &x);
int k = linearSearch(arr, size, x);
}
return 0;
}
There is one major problem in your code.
First you need to pass address of your array element(&arr[j]
).
And the output is not displaying because you are not printing it out.
The correct code is
#include <stdio.h>
int linearSearch(int arr[], int size, int element)
{
int i = 0;
for(i=0; i< size; i++)
{
if(arr[i] == element)
{
return i;
}
}
return 0;
}
int main()
{
int turns, size;
scanf("%d", &turns);
while(turns--)
{
scanf("%d", &size);
int arr[size];
for(int j=0; j < size; j++)
{
scanf("%d", &arr[j]);
}
int x;
scanf("%d", &x);
int k = linearSearch(arr, size, x);
printf("%d\n", k);
}
return 0;
}