C Program to Store City Names and Search Using Linear Search
In C programming, we can store multiple city names using a 2D character array. In this program, we will accept city names and use Linear Search to check whether a given city is present or not.
📝 Problem Statement
Q1. 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.
💡 Logic (Simple Student-Friendly Steps)
- Declare a 2D character array to store city names.
- Read number of cities (n).
- Accept city names using a loop.
- Accept a city name to search.
- Use a
forloop to compare each city name with the search name usingstrcmp(). - If match found → display “City Found”.
- Otherwise → display “City Not Found”.
👉 We use strcmp() to compare strings in C.
💻 Source Code (Simple Version)
#include <stdio.h>
#include <string.h>
int main()
{
char city[100][50], search[50];
int n, i, found = 0;
printf("Enter number of cities: ");
scanf("%d", &n);
printf("Enter city names:\n");
for(i = 0; i < n; i++)
{
scanf("%s", city[i]);
}
printf("Enter city name to search: ");
scanf("%s", search);
for(i = 0; i < n; i++)
{
if(strcmp(city[i], search) == 0)
{
found = 1;
break;
}
}
if(found == 1)
printf("City found in the list.");
else
printf("City not found in the list.");
return 0;
}
🖥️ Sample Output
Enter number of cities: 4
Enter city names:
Pune
Mumbai
Delhi
Chennai
Enter city name to search: Delhi
City found in the list.
Another Sample Output
Enter number of cities: 3
Enter city names:
Nagpur
Nashik
Kolhapur
Enter city name to search: Jaipur
City not found in the list.
🎓 Viva Questions with Answers
1. What is Linear Search?
Linear search checks each element one by one until the required element is found.
2. Why do we use strcmp()?
Because strings cannot be compared using == in C.
3. What is a 2D character array?
It is an array used to store multiple strings.
4. What is the time complexity of Linear Search?
O(n).
5. Does Linear Search require sorting?
No, sorting is not required.
