SYBCom(CA) DS Practical Slip 4 Q.A

Write a ‘C’ program to accept the names of cities and store them in array. Accept the city name from user and use linear search algorithm to check whether the city is present in array or not.

#include <stdio.h>
#include <string.h>

#define MAX 100
#define SIZE 50

int main() {
    int n, i, found = 0;
    char cities[MAX][SIZE];
    char searchCity[SIZE];

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

    // Accept city names
    printf("Enter %d city names:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%s", cities[i]);
    }

    // Accept city to search
    printf("Enter city name to search: ");
    scanf("%s", searchCity);

    // Linear Search
    for(i = 0; i < n; i++) {
        if(strcmp(cities[i], searchCity) == 0) {
            found = 1;
            break;
        }
    }

    // Display result
    if(found)
        printf("City '%s' is present in the list at position %d.\n", searchCity, i + 1);
    else
        printf("City '%s' is NOT present in the list.\n", searchCity);

    return 0;
}
Spread the love

Leave a Comment

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

Scroll to Top