Find the nearest lesser and nearest greater number in an array
C program to find the nearest lesser and nearest greater number, to the number entered, from the array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
int arr[MAX];
int i, n, num, diff;
int near_small, near_big, big_diff, small_diff;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&arr[i]);
}
printf("\nEnter the number from which nearest lesser and nearest greater is to be found\t:");
scanf("%d",&num);
near_big = 0;
near_small = 0;
diff = 0;
for(i=0;i<n;i++)
{
if(arr[i] > num)
{
diff = arr[i] - num;
if(diff < big_diff)
{
near_big = arr[i];
big_diff = diff;
}
}
else if(arr[i] < num)
{
diff = num - arr[i];
if(diff < small_diff)
{
near_small = arr[i];
small_diff = diff;
}
}
}
if(near_big == 0)
{
printf("\nNearest lesser number\t:%d",near_small);
printf("\nNearest greater number does not exist");
}
else if(near_small == 0)
{
printf("\nNearest lesser number does not exist");
printf("\nNearest greater number\t:%d",near_big);
}
else
{
printf("\nNearest lesser number\t:%d",near_small);
printf("\nNearest greater number\t:%d",near_big);
}
getch();
}
Output
********** Run1 **********
Enter the number of elements in the array :4
Enter the elements
Element 1 :45
Element 2 :12
Element 3 :56
Element 4 :23
Enter the number from which nearest lesser and nearest greater is to be found :30
Nearest lesser number :23
Nearest greater number :45
********** Run2 **********
Enter the number of elements in the array :4
Enter the elements
Element 1 :45
Element 2 :52
Element 3 :56
Element 4 :23
Enter the number from which nearest lesser and nearest greater is to be found :23
Nearest lesser number does not exist
Nearest greater number :45
********** Run3 **********
Enter the number of elements in the array :4
Enter the elements
Element 1 :41
Element 2 :52
Element 3 :12
Element 4 :56
Enter the number from which nearest lesser and nearest greater is to be found :56
Nearest lesser number :52
Nearest greater number does not exist