TO SEARCH FOR A NUMBER IN A LIST OF NUMBERS
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10},n,i,f,s;
clrscr();
printf("Enter the no of numbers \n");
scanf("%d",&n);
printf("Enter %d numbers \n",n);
for(i=0;i<n;i++)
scanf("%d",a[i]);
printf("Enter the number to be searched \n");
scanf("%d",&s);
/* searching for s in a begins */
f=0;
for(i=0;i<n;i++)
if(a[i]==s)
{
f=1;
break;
}
/*searching for s in a ends*/
printf("\n List of elements \n");
for(i=0;i<n;i++)
printf("%d",a[i]);
printf("\n Enter to be searched \n");
printf("\n s=%d \n",s);
if(f==1)
printf("%d is found",s);
else
printf("%d is not found",s);
getch();
}
OUTPUT
Enter the no of numbers
5
Enter 5 numbers
1 2 3 4 5
Enter the number to be searched
3
List of elements
1 2 3 4 5
Elements to be searched
3
3 is found
Explanation
a is declared to be array of int type of size 10.Maximum 10 values can be read into the array.n,i,s and f are declared to be variable of int type.n is to collect the number of values to be read into a, which lies within 1 and 10.i is to traverse all the elements of a.s is to collect a value which is to be searched.f is to be determine whether s is found in a or not.It acts as a flag variable.The procedure of searching for s in a is implemented in the following segment of the program.
f=0;
for(i=0;i<n;i++)
if(a[i]==s)
{
f=1;
break;
}
before searching begins,f is set to zero with the assumption that s is not available in a.During the course of searching that is inside the body of the for loop, if s is found t match with any element in the array, f is set to 1 and loop is excited. If s takes 1 then it means s is found in a.If f retains 0,we conclude that s s not fond in a.The value of f would thus tell us whether s is found in a or not.
No comments:
Post a Comment