Why are my while loops not working? I m getting no error, but also no output.
Codes are working perfectly fine uptil the main logic.
example my output for binary search is : Enter the array size: 5
Enter array elements in sorted form : 1 2 3 4 5 Enter the target element: 2
//no output is shown after this user input (NOTE: Same logics are perrfectly working with for loops)
//Code for Binary search (while loop not working )
#include<stdio.h>
#define max 20
int main(){
int a[max],n,i,target;
int l=0;
int r=n-1;
int mid=(l+r)/2;
printf("\nEnter the array size: \n");
scanf("%d",&n);
printf("\nEnter array elements in sorted form : \n");
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("Enter the target element: ");
scanf("%d",&target);
while(l<=r){
if(target==a[mid]){
printf("Element found at %d position",i+1);
}
else if(target<a[mid]){
r=mid-1;
}
else{
l=mid+1;
}
}
return 0;
}
//Same problem with linear search while loop
#include<stdio.h>
#define max 20
int main(){
int array[max],target,size,i=0,flag=0;
printf("Enter the size of array: ");
scanf("%d",&size);
printf("Enter the elements of array: ");
for(i=0;i<size;i++){
scanf("%d",&array[i]);
}
printf("Enter the element to be found in array: ");
scanf("%d",&target);
printf("Target accepted");
while( i < size ) {
if(array[i]==target){
printf("Element found at %d position",i+1);
flag=1;
break;
}
else{
flag=0;
}
i++;
}
if(flag==0){
printf("Element not found !!!");
}
return 0;
}