Skip to content

Commit 982a075

Browse files
committed
dynamic memory allocation in linear_search.c
1 parent 579738f commit 982a075

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

search/linear_search.c

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
11
#include <stdio.h>
2-
2+
#include <stdlib.h>
33
int main()
44
{
5-
int array[100], search, c, n;
5+
int *array, search, c, n_terms;
66

77
printf("Enter the number of elements in array\n");
8-
scanf("%d",&n); // Total no of elements
8+
scanf("%d",&n_terms); // Total no of elements
99

10-
printf("Enter %d integer(s)\n", n);
10+
array = (int*)malloc(sizeof(int)*n_terms);
11+
printf("Enter %d integer(s)\n", n_terms);
1112

12-
for (c = 0; c < n; c++)
13+
for (c = 0; c < n_terms; c++)
1314
scanf("%d", &array[c]); // Reading the elements
1415

1516
printf("Enter the number to search\n"); // Target element to be searched
1617
scanf("%d", &search);
1718

18-
for (c = 0; c < n; c++)
19+
for (c = 0; c < n_terms; c++)
1920
{
2021
if (array[c] == search) /* if required element found */
2122
{
2223
printf("%d is present at location %d.\n", search, c+1);
2324
break;
2425
}
2526
}
26-
if (c == n)
27+
if (c == n_terms)
2728
printf("%d is not present in array.\n", search); // Element not found
2829

2930
return 0;

0 commit comments

Comments
 (0)