Qn-3.c (1484B)
1 /* 2 * Author : Amit Dutta <amitdutta4255@gmail.com> 3 * Date : 06 Mar 2026 4 * Repo : https://github.com/notamitgamer/bsc 5 * License : MIT License (See the LICENSE file for details) 6 */ 7 8 /* Write a program to search an element from an array using linear 9 search technique using malloc() and free() for memory allocation 10 and deallocation. */ 11 12 #include <stdio.h> 13 #include <stdlib.h> 14 15 int inputArray(int[], int); 16 int linearSearch(int[], int, int); 17 18 int main() 19 { 20 int size, *arr = NULL; 21 printf("How many element do you want to enter: "); 22 scanf("%d", &size); 23 arr = (int *)malloc(size * sizeof(int)); 24 if (arr == NULL) 25 { 26 printf("Memory allocation failed! Exiting...\n"); 27 return 1; 28 } 29 int target = inputArray(arr, size); 30 int index = linearSearch(arr, size, target); 31 if (index != -1) 32 { 33 printf("\nElement %d is found at index %d.", target, index); 34 } 35 else 36 { 37 printf("\nElement %d is not found.", target); 38 } 39 free(arr); 40 return 0; 41 } 42 43 int inputArray(int arr[], int size) 44 { 45 int i, target; 46 for (i = 0; i < size; i++) 47 { 48 printf("Enter element for position %d: ", i); 49 scanf("%d", &arr[i]); 50 } 51 printf("\nEnter the target element: "); 52 scanf("%d", &target); 53 return target; 54 } 55 56 int linearSearch(int arr[], int size, int target) 57 { 58 for (int i = 0; i < size; i++) 59 { 60 if (arr[i] == target) 61 { 62 return i; 63 } 64 } 65 return -1; 66 }