C PROGRAM
Program to search an element of an array |C Program|
Introduction
Searching for an element in an array is a common task in programming, especially when dealing with large sets of data. In this blog post, we'll explore a C program that performs a simple linear search to find an element within an array. Understanding array manipulation and searching algorithms is fundamental for aspiring programmers.
Code
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,item;
clrscr();
printf("how many elements you want to enter:");
scanf("%d",&n);
printf("enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the elements to be searched:");
scanf("%d",&item);
for(i=0;i<n;i++)
{
if(item==a[i])
{
printf("%d found at the position %d",item,i+1);
break;
}
}
if(i==n)
printf("item %d not found at in the array ",item);
getch();
}
Output
how many elements you want to enter:5
enter the elements:
1
2
3
4
5
enter the elements to be searched:3
3 found at the position 3
Explanation
1. Header Files:
The program includes the standard input/output header <stdio.h> and the console I/O header <conio.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter the number of elements and the elements themselves into an array a.
3. Linear Search Operation:
A for loop iterates through each element in the array.
The loop compares each element with the user-inputted item.
If a match is found, the program prints the element and its position and breaks out of the loop.
4. Result Display:
Depending on whether the item is found or not, the program prints either its position in the array or a message indicating that it was not found.
5. User Interaction:
Users receive clear feedback about whether the entered element is present in the array and its position if applicable.
Conclusion
This C program provides a straightforward implementation of a linear search operation in an array. While linear search is a basic method, it's important to note that more advanced algorithms, such as binary search, exist for larger datasets.
Experiment with different array sizes and elements, analyze the flow of the program, and consider optimizations or alternative search algorithms. Understanding these fundamental concepts is crucial for building a strong foundation in programming. Happy coding!
Post a Comment
0 Comments