Skip to content
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

LinearSearchRecursion.c #468

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
44 changes: 44 additions & 0 deletions C Language/LinearSearchRecursion.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <stdio.h>

int linearSearchRecursive(int arr[], int size, int target, int index, int *counter) {
if (index >= size) {
return -1;
}

(*counter)++;

if (arr[index] == target) {
return index;
}

return linearSearchRecursive(arr, size, target, index + 1, counter);
}

int main() {
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);

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

int target;
printf("Enter the target value to search for: ");
scanf("%d", &target);

int counter = 0;
int result = linearSearchRecursive(array, size, target, 0, &counter);

if (result != -1) {
printf("Target %d found at index %d\n", target, result);
} else {
printf("Target %d not found in the array\n", target);
}

printf("Total comparisons made: %d\n", counter);

return 0;
}