You can create your own libraries easily. As an example, we will take some code from a previous article in this series and make a library out of two of its functions. Here's the code we will start with:
#include <stdio.h>
#define MAX 10
int a[MAX];
int rand_seed=10;
int rand()
/* from K&R
- produces a random number between 0 and 32767.*/
{
rand_seed = rand_seed * 1103515245 +12345;
return (unsigned int)(rand_seed / 65536) % 32768;
}
void main()
{
int i,t,x,y;
/* fill array */
for (i=0; i < MAX; i++)
{
a[i]=rand();
printf("%d\n",a[i]);
}
/* bubble sort the array */
for (x=0; x < MAX-1; x++)
for (y=0; y < MAX-x-1; y++)
if (a[y] > a[y+1])
{
t=a[y];
a[y]=a[y+1];
a[y+1]=t;
}
/* print sorted array */
printf("--------------------\n");
for (i=0; i < MAX; i++)
printf("%d\n",a[i]);
}
This code fills an array with random numbers, sorts them using a bubble sort, and then displays the sorted list.
Take the bubble sort code, and use what you learned in the previous article to make a function from it. Since both the array a and the constant MAX are known globally, the function you create needs no parameters, nor does it need to return a result. However, you should use local variables for x, y, and t.
Once you have tested the function to make sure it is working, pass in the number of elements as a parameter rather than using MAX:
#include <stdio.h>
#define MAX 10
int a[MAX];
int rand_seed=10;
/* from K&R
- returns random number between 0 and 32767.*/
int rand()
{
rand_seed = rand_seed * 1103515245 +12345;
return (unsigned int)(rand_seed / 65536) % 32768;
}
void bubble_sort(int m)
{
int x,y,t;
for (x=0; x < m-1; x++)
for (y=0; y < m-x-1; y++)
if (a[y] > a[y+1])
{
t=a[y];
a[y]=a[y+1];
a[y+1]=t;
}
}
void main()
{
int i,t,x,y;
/* fill array */
for (i=0; i < MAX; i++)
{
a[i]=rand();
printf("%d\n",a[i]);
}
bubble_sort(MAX);
/* print sorted array */
printf("--------------------\n");
for (i=0; i < MAX; i++)
printf("%d\n",a[i]);
}
You can also generalize the bubble_sort function even more by passing in a as a parameter:
bubble_sort(int m, int a[])
This line says, "Accept the integer array a of any size as a parameter." Nothing in the body of the bubble_sort function needs to change. To call bubble_sort, change the call to:
bubble_sort(MAX, a);
Note that &a has not been used in the function call even though the sort will change a. The reason for this will become clear once you understand pointers.
More Options: