Linear search program

#include <stdio.h>
int main() {
int a[10];
int key,n,i,flag=0;
printf(“Enter the size of array\n”);
scanf("%d",&n);
printf(“Enter the elements\n”);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the key\n ");

scanf("%d",&key);
for(i=0;i<n;i++){
    if(key==a[i]){
        flag=1;
    }
}
if(flag=1){
    printf("Found!\n");

}
else{
    printf("Not found\n");
}
return 0;

}

For every input for key the program returns found. Where’s the mistake?

Hi @sirprashar, check the if statement just after loop ends. Also try to optimize your code by skipping extra iterations. You can do that with the help of a keyword/statement in C.

if(flag=1)
changes to
if(flag==1){