Program 112:
Explanation:#include<stdio.h>
main()
{
int i,n,search,flag=0;
printf("Enter size of array\n");
scanf("%d",&n);
int a[n];
printf("Enter the numbers\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched\n");
scanf("%d",&search);
for(i=0;i<n;i++)
{
if(a[i]==search)
{
flag=1;
}
}
if(flag==1)
{
printf("Search Successful\n");
}
else
{
printf("Search is not Successful\n");
}
}
- Declaring i,n,search,flag=0,a[n]
- n→ To store size of array
- i →Used as helping variable
- search→ To store number we need to search
- flag→ To store if search is sucessfull or not
- a[n]→ To store all the numbers given by user from which we need to find the searching number
printf("Enter the numbers\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); }To take all numbers from user and storing them in array 'a' one by oneprintf("Enter the element to be searched\n"); scanf("%d",&search);Storing the number in the search variable- Main logic of program
for(i=0;i<n;i++) { if(a[i]==search) { flag=1; } } - We are iterating from 0 till n (say if n=6) as in below output and array a contains numbers of 103,406,-1000,54,32,789 and our search= -1000.
- We will iterate one by one through for loop :
- Iteration 1: i=0 and a[0]=103 and a[0]==-1000 i,e 103==-1000 is false. Then proceed to next iteration and i will be incremented by 1
- Iteration 2: i=1 and a[1]=406 and a[1]==-1000 i,e 406==-1000 is false. Then proceed to next iteration and i will be incremented by 1 \
- Iteration 3: i=2 and a[2]=-1000 and a[2]==-1000 i,e -1000==-1000 is true. so update flag to 1
- The same way iteration will go till i=5 and flag =1 after 3rd iteration
if(flag==1) { printf("Search Successful\n"); } else { printf("Search is not Successful\n"); }
- Since flag==1 which is true. "Search Successful" will be printed as output
Output:


