Search an array of integers for a VAL value entered on the keyboard. Display the position of VAL if it is in the array, otherwise display a corresponding message. The INDEX value that is used to memorize the position of the value in the array, will have the value -1 as long as VAL was not found.

Method: Successively compare the values of the array with the given value.


Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 50
void main()
{
	int A[SIZE], N, val;
	int i;
	int index;

	do {
		printf("Enter the dimension: ");
		scanf("%d", &N);
	} while (N <= 0 || N > SIZE);

	for (i = 0; i < N; i++)
	{
		printf("Enter A[%d]: ", i);
		scanf("%d", &A[i]);
	}

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

	 /* find the index of val */
 	index = -1; // not found yet
 	for (i=0 ; (i<N)&&(index==-1) ; i++)
       		if (A[i]==val)
           		index=i;


 	if (index==-1)
     		printf("%d not found in the array.\n", val);
  	else
     		printf("%d is found at index %d.\n", val, index);

	getch();
}


Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Zeroing duplicated elements in an array