Exercise 5

Write a C program to interchange the largest and smallest numbers in the array.

SOURCE CODE:

/*Program to interchange largest and smallest numbers in the array.*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int a[30],largest,smallest,i,j,k,n,temp;
 clrscr();
 printf("\nEnter the array size:");
 scanf("%d",&n);
 printf("\nEnter %d elements:",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 largest=smallest=a[0];
 for(i=0;i<n;i++)
 {
  if(largest<=a[i])
  {
   largest=a[i];
   j=i;
  }
  if(smallest>=a[i])
  {
   smallest=a[i];
   k=i;
  }
 }
 temp=a[j];
 a[j]=a[k];
 a[k]=temp;
 printf("\nAfter interchange array is:\n");
 for(i=0;i<n;i++)
  printf("%d\t",a[i]);
}

OUTPUT:












Write a C program to implement a liner search.

SOURCE CODE:

/*Program to implement a linear search.*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int a[30],n,i,key,temp=0;
 clrscr();
 printf("\nEnter the array size:");
 scanf("%d",&n);
 printf("\nEnter %d elements:\n",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 printf("\nEnter key value:");
 scanf("%d",&key);
 for(i=0;i<n;i++)
 {
  if(a[i]==key)
  {
   temp=1;
   break;
  }
 }
 if(temp==1)
  printf("\nKey value is found at %d position.",i);
 else
  printf("\nKey value is not found.");

}

OUTPUT:

























Write a C program to implement binary search.

SOURCE CODE:

/*Program to implement binary search.*/
#include<stdio.h>
#include<conio.h>
void main()
{
 int a[30],n,i,key,low,high,mid,temp=0;
 clrscr();
 printf("\nEnter the array size:");
 scanf("%d",&n);
 printf("\nEnter %d elements in sorted order:\n",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 printf("\nEnter key value:");
 scanf("%d",&key);
 low=0;
 high=n-1;
 while(low<=high)
 {
  mid=(low+high)/2;
  if(a[mid]==key)
  {
   temp=1;
   break;
  }
  else if(a[mid]<key)
   low=mid+1;
  else
   high=mid-1;
 }
 if(temp==1)
  printf("\nKey value is found at %d position.",mid);
 else
  printf("\nKey value is not found.");
}

OUTPUT:


No comments:

Post a Comment

Total Pageviews