Skip to content

Improved linear search: return index, input validation, multpile queries #1474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 47 additions & 17 deletions searching/linear_search.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,63 @@

int linearsearch(int *arr, int size, int val)
{
int i;
for (i = 0; i < size; i++)
for (int i = 0; i < size; i++)
{
if (arr[i] == val)
return 1;
return i; // Return index if found
}
return 0;
return -1; // Not found
}

void printArray(int *arr, int size)
{
printf("Array contents: ");
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main()
{
int n, i, v;
int n;
printf("Enter the size of the array:\n");
scanf("%d", &n); // Taking input for the size of Array
scanf("%d", &n);

if (n <= 0)
{
printf("Invalid array size!\n");
return 1;
}

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

printf("Enter the value to be searched:\n");
scanf("%d", &v); // Taking input the value to be searched
if (linearsearch(a, n, v))
printf("Value %d is in the array.\n", v);
else
printf("Value %d is not in the array.\n", v);
if (a == NULL)
{
printf("Memory allocation failed!\n");
return 1;
}

printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);

printArray(a, n);

char choice;
do
{
int v;
printf("Enter the value to be searched:\n");
scanf("%d", &v);

int index = linearsearch(a, n, v);
if (index != -1)
printf("Value %d is in the array at index %d.\n", v, index);
else
printf("Value %d is not in the array.\n", v);

printf("Search again? (y/n): ");
scanf(" %c", &choice); // The space before %c eats the leftover newline
} while (choice == 'y' || choice == 'Y');

free(a);
return 0;
Expand Down