SYBCom(CA) DS Practical Slip 3 Q.A

Write a C program to accept n elements from user store it in an array. Accept a
value from the user and use linear/Sequential search method to check whether the value is
present in array or not. Display proper message.

#include <stdio.h>

int main() {
    int n, i, value, found = 0;

    printf("Enter number of elements: ");
    scanf("%d", &n);

    int arr[n];

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

    // Accept value to search
    printf("Enter value to search: ");
    scanf("%d", &value);

    // Linear Search
    for(i = 0; i < n; i++) {
        if(arr[i] == value) {
            found = 1;
            break;
        }
    }

    // Display result
    if(found)
        printf("Value %d is present in the array at position %d.\n", value, i + 1);
    else
        printf("Value %d is NOT present in the array.\n", value);

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top