C Program to Linear Search in an Sorted Array

In a linear search, you iterate through each element of an array until you find the target element or reach the end of the array. In the case of a sorted array, you can optimize the search process by stopping the search when you find an element greater than the target, as it implies the target won’t be found in the remaining elements.

Here’s a simple example of a C program for linear search in a sorted array

Program :

#include <stdio.h>
#include <conio.h>
 
void main( )
{
int arr[10];
int i,n,num ;
printf(“Enter the number of Elements : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“Element%d : “,i+1);
scanf(“%d”,&arr[i]);
}
printf ( “Enter number to search: ” ) ;
scanf ( “%d”, &num ) ;
 
for ( i = 1 ; i <= n ; i++ )
{
if ( arr[n] < num || arr[i] >= num )
{
if ( arr[i] == num )
printf ( “The number is at position %d in the array.”, i ) ;
else
printf ( “Number is not present in the array.” ) ;
break ;
}
}
 
getch( ) ;
}

Output :

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Basket
Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare
Verified by MonsterInsights