bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / eduincs_exam / Paper-2_05-03-2026 / Qn-3.c

Qn-3.c (1293B)


      1 /* Write a program to search an element from an array using linear
      2 search technique using malloc() and free() for memory allocation
      3 and deallocation. */
      4 
      5 #include <stdio.h>
      6 #include <stdlib.h>
      7 
      8 int inputArray(int[], int);
      9 int linearSearch(int[], int, int);
     10 
     11 int main()
     12 {
     13     int size, *arr = NULL;
     14     printf("How many element do you want to enter: ");
     15     scanf("%d", &size);
     16     arr = (int *)malloc(size * sizeof(int));
     17     if (arr == NULL)
     18     {
     19         printf("Memory allocation failed! Exiting...\n");
     20         return 1;
     21     }
     22     int target = inputArray(arr, size);
     23     int index = linearSearch(arr, size, target);
     24     if (index != -1)
     25     {
     26         printf("\nElement %d is found at index %d.", target, index);
     27     }
     28     else
     29     {
     30         printf("\nElement %d is not found.", target);
     31     }
     32     free(arr);
     33     return 0;
     34 }
     35 
     36 int inputArray(int arr[], int size)
     37 {
     38     int i, target;
     39     for (i = 0; i < size; i++)
     40     {
     41         printf("Enter element for position %d: ", i);
     42         scanf("%d", &arr[i]);
     43     }
     44     printf("\nEnter the target element: ");
     45     scanf("%d", &target);
     46     return target;
     47 }
     48 
     49 int linearSearch(int arr[], int size, int target)
     50 {
     51     for (int i = 0; i < size; i++)
     52     {
     53         if (arr[i] == target)
     54         {
     55             return i;
     56         }
     57     }
     58     return -1;
     59 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror