Here we are going to write a c program to search an element in an array using function. There are many searching techniques like Linear Search, Binary Search etc. We will do this program using linear search method.
First we will create a function named search() of void return type and it will take two integers one array and other is the number which we want to search. Then within that function we will check whether the given number is present in the array or not. If found we will return the index and if not we display "Number not found" print the pattern. Then in main() function we will call the search() function, that's it. Now lets code it.
C Program to Search an Element in an Array using Function
#include <stdio.h>
void search(int arr[], int n){
int c=0;
for(int i=0;i<n; i++){
if(arr[i]==n){
printf("Number found at %d", i);
c++;
break;
}
}
if(c==0){
printf("Number not found!");
}
}
int main(){
int n;
int arr[]={1,2,3,4,5,6,7,8};
printf("Enter number to find: ");
scanf("%d",&n);
search (arr,n);
return 0;
}Output
Enter number to find: 7
Number found at 6More like this
• Program to implement Binary Search
• Program to print pyramid pattern of numbers using function
• Program to print inverted pyramid pattern of numbers using function
• Factorial of a number program in c using function
• Prime Number check in C using function
• Palindrome Number in C using function

Post a Comment
If you have any doubts, please let me know