Explanation of the program
This program uses linear search to find an element in an array. The elements are read into the array a[]. The element to be searched is read into the variable n. The for loop uses the loop variable i, at each iteration in the for loop the value of a[i] is compared with the value of n, if a match is found, the execution of for loop is terminated and the value of i gives the position of the element. The variable flag is initially set to 0, if a match is found during the search in the array flag will be set to 1. After exiting from the for loop, if the value of flag is 0, then the item is not present in the array.
Program
#include<stdio.h> #include<conio.h> void main() { int a[10],n,flag=0; clrscr(); printf("Enter the numbers"); for(int i=0;i<10;i++) { scanf("%d",&a[i]); } printf("Enter the item to be searched"); scanf("%d",&n); for(i=0;i<10;i++) { if(a[i]==n) { printf("Item %d found at location %d",n,i); flag=1; break; } } if(flag==0) { printf("Item not found in the array"); } getch(); }
No comments:
Post a Comment