Skip to content

Commit e2feb40

Browse files
authored
Update linear_search.c
1. If The Element Is Found - linearsearch() function will return the index of that element which will later get printed out through the main() function. 2. If The Element Is Not Found - linearsearch() function will return 0.
1 parent e5dad3f commit e2feb40

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

searching/linear_search.c

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,29 @@ int linearsearch(int *arr, int size, int val)
77
for (i = 0; i < size; i++)
88
{
99
if (arr[i] == val)
10-
return 1;
10+
return i;
1111
}
1212
return 0;
1313
}
1414

1515
int main()
1616
{
17-
int n, i, v;
17+
int n, i, v, r;
1818
printf("Enter the size of the array:\n");
19-
scanf("%d", &n); // Taking input for the size of Array
19+
scanf("%d", &n); // Taking input for the size of Array
2020

2121
int *a = (int *)malloc(n * sizeof(int));
2222
printf("Enter the contents for an array of size %d:\n", n);
2323
for (i = 0; i < n; i++)
24-
scanf("%d", &a[i]); // accepts the values of array elements until the
25-
// loop terminates//
24+
scanf("%d", &a[i]); // accepts the values of array elements until the
25+
// loop terminates//
2626

2727
printf("Enter the value to be searched:\n");
28-
scanf("%d", &v); // Taking input the value to be searched
29-
if (linearsearch(a, n, v))
30-
printf("Value %d is in the array.\n", v);
28+
scanf("%d", &v); // Taking input the value to be searched
29+
30+
r = linearsearch(a, n, v);
31+
if (r != 0)
32+
printf("Value %d is in the array at index %d.\n", v, r);
3133
else
3234
printf("Value %d is not in the array.\n", v);
3335

0 commit comments

Comments
 (0)