Below is a C program which allows an user to enter a maximum of 10 numbers. It also allows an user to search whether a given number is available or not. If the given number is available, the program displays the index within the array at which the number is found.
/*Program to search for a given number in an array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[10],n,i,num,flag=0;
printf("How many numbers you want to enter:");
scanf("%d",&num);
if(num>10||num<1)
{
printf("Size cannot be greater than 10 and less than 1.Try again...!");
}
else
{
/*Reading the array elements*/
printf("Enter the array elements:\n");
for(i=0;i<num;i++)
{
scanf("%d",&arr[i]);
}
/*Reading the number to search in the array*/
printf("Enter the number you want to search:");
scanf("%d",&n);
/*Code to check if the number is available in the array or not*/
for(i=0;i<num;i++)
{
if(arr[i]==n)
{
printf("%d is found at index %d\n",n,i);
flag = 1;
}
}
if(flag==0)
printf("Given number is not available in the array.");
}
getch();
}
Sample input and output:
How many numbers you want to enter:5
Enter the array elements:
1 2 3 4 5
Enter the number you want to search:3
3 is found at index 2
No comments:
Post a Comment