Transcript Lecture 8

Programming examples
on Functions
Department of Computer Science
Linear search using functions
We make use of 3 functions namely:
1. input( ); to read the n elements of the array.
2. linear_search( ); to search for the element in the list.
3. main( ) – that calls the function input & linear_search
Define the variables as global, i.e. int i,n,a[20],key;
Function input( ) – to accept the numbers from the keyboard.
void input( )
{
for (i=0; i<n; i++)
scanf (“%d”,&a[i]);
}
void search()
{
for(i=0;i<n;i++)
{
if(a[i]==key)
{
printf(“\nsuccessful the element is found and at position=%d”,i+1);
exit(0);
getch();
}
}
printf(“\n element is not found:unsuccessful”);
}
void main()
{
printf(“\n enter the number of elements”);
scanf (“%d”,&n);
printf(“\n enter the array elements\n”);
input();
printf(“\n enter the element to be searched”);
scanf(“%d”,&key);
search();
}
Bubble sort using functions
We make use of 4 functions namely:
1. input( ); to read the n elements of the array.
2. Output( ): to display the sorted elements.
2. bubble( ); to sort the elements either in ascending/ descending order.
3. main( ) – that calls the function input, output & bubble
Define the variables as global, i.e. int i,j,n,a[20],temp;
Function input( ) – to accept the numbers from the keyboard.
void input( )
{
for (i=0; i<n; i++)
scanf (“%d”,&a[i]);
}
function output( ) – to display the sorted numbers
void output( )
{
for (i=0; i<n; i++)
printf (“%d\n”,a[i]);
}
function bubble( ) – to sort the numbers in ascending order
void bubble( )
{
for (j=1; j<n; j++)
{
for (i=0; i<n-j; i++)
{
if(a[i] > = a[i+1])
{
temp=a[i];
a[i]=a[i+1]
a[i+1]=temp;
}
}
}
}
void main()
{
printf(“\n enter the number of elements”);
scanf (“%d”,&n);
printf(“\n enter the array elements\n”);
input();
printf(“\n enter the element to be sorted”);
bubble();
printf(“\n the sorted array elements in ascending order”);
output();
}
Selection sort using functions
We make use of 4 functions namely:
1. input( ); to read the n elements of the array.
2. Output( ): to display the sorted elements.
2. select( ); to sort the elements either in ascending/ descending order.
3. main( ) – that calls the function input, output & bubble
Define the variables as global, i.e. int i,j,n,a[20],temp,loc;
Function input( ) – to accept the numbers from the keyboard.
void input( )
{
for (i=0; i<n; i++)
scanf (“%d”,&a[i]);
}
function output( ) – to display the sorted numbers
void output( )
{
for (i=0; i<n; i++)
printf (“%d\n”,a[i]);
}
function select( ) – to sort the numbers in ascending order
void select( )
{
for (i=0; i<n-1; i++)
{
loc=i;
for (j=i+1; j<n;j++)
{
if(a[i]< a[loc])
loc=j;
}
temp=a[loc];
a[loc]=a[i]
a[i]=temp;
}
}
void main()
{
printf(“\n enter the number of elements”);
scanf (“%d”,&n);
printf(“\n enter the array elements\n”);
input();
printf(“\n enter the element to be sorted”);
select();
printf(“\n the sorted array elements in ascending order”);
output():
}