Write a C program that uses non-recursive function to search for a Key value in a given list of integers using linear search method.
Write a C program that uses non-recursive function to search for a Key value in a given list of integers using linear search method.
C Programming
//A non-recursive function to search for a Key value in a given list of integers using linear search method.
#include <stdio.h>
int main() {
int n, i, key, arr[20];
int linearSearch(int [], int , int );
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter key to search: ");
scanf("%d", &key);
int result = linearSearch(arr, n, key);
if (result == -1)
printf("Key %d not found in the list.\n", key);
else
printf("Key %d found at position %d (index %d).\n", key, result + 1, result);
return 0;
}
// Function to perform linear search (non-recursive)
int linearSearch(int arr[], int n, int key)
{
int i;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
return i; // return index if key is found
}
return -1; // key not found
}
OUTPUT
Enter number of elements: 10
Enter 10 integers:
4 5 6 7 8 9 1 2 3 0
Enter key to search: 9
Key 9 found at position 6 (index 5).
๐ป Run This C Program
Write a C program that uses non-recursive function to search for a Key value in a given list of integers using linear search method.
The selected C program is loaded automatically. Edit the code,
provide input through STDIN and click Run.
The compiler is embedded using OneCompiler. Your program runs in
the embedded C environment; Study Glance does not execute C code
directly on your web server.