Decode School

Decode School - The School for Problem Solvers

Welcome to my blog. Subscribe and get my latest blog post in your inbox.

C Program to Search an Element in an array

Get an element and find the location of element in array, print -1 if element is not found.

Sample Input 1:

5 5 7 9 3 1 9

Sample Output 1:

2

Sample Input 2:

5 5 7 9 3 1 4

Sample Output 2:

-1

Program or Solution

					    
							
#include <stdio.h>
#include <stdlib.h>


int main(void)

{
	
	int *a,n,i,pos=-1,element;

	printf("Enter size of array:");
	scanf("%d",&n);

	a=malloc(sizeof(int)*n);

	printf("Enter %d Elements:",n);
	for(i=0;i<n;i++)

	{

		scanf("%d",&a[i]);

	}

	printf("Enter a element to find:");
	scanf("%d",&element);

	
	for(i=0;i<n;i++)
	
	{

		if(a[i]==element)
		{
			pos=i;
			break;
		}
	}

	printf("%d is in %d",element,pos);	
	return 0;

}
					    
					

Program Explanation

i is initialized to 0 and incremented by 1 at each iteration of both the for loops.

First for loop reads n input numbers from user and stores them in array a[] from location 0 to n-1 using Second for loop the element is searched in each location from 0 to the location of element or location n-1.

if element is found in a location that location i is stored as pos and exit from the for loop using break statement.

if element is not found from 0 to n-1 location, pos remains -1.