Saturday, May 8, 2021

Search an Element in Array Using C

 This example will show you how to search an element in an Array using C program.

Search an Element in Array Using C


The below search function takes four arguments

int search(int *a, int n, int k)


*a – pointer to an array

n – size of the array

k – the element to be searched in array


Example

#include<stdio.h>

int search(int *a, int n, int k){
	int i;
	for(i=0;i<n;i++){
		if(a[i]==k){
			return i;
		}
	}
	return -1;
}

main(){
	int i;
	int a[50];
	int searchIndex;
	for(i=0;i<50;i++){
		a[i]=i+100;
	}
	searchIndex = search(a,50,135);
	if(searchIndex != -1){
		printf("Search found at array index %d", searchIndex);
	}else{
		printf("Element not found in array");
	}
	return 0;
}


Output

Search found at array index 35



No comments:

Post a Comment