foo( a ), we'd really be passing a pointer to the first
element in the array.
With that in mind, we can write a routine to print out the elements
in an integer array like this.
![]()
void print_array( int a[], int num )
{
int i ;
for( i = 0; i < num; ++i )
printf( "%d\n", a[i] ) ;
}
![]()
print_array() as
![]()
void print_array( int *a; int num )
![]()
Another thing to notice about "passing arrays" is that since we're passing
a pointer, changes made to the array in the function are seen by the caller
unlike when we pass basic types like integers.
This is why, when calling scanf() or
gets(), we just give the
name of the character array instead of using the & operator
as we do for integers in scanf().
This feature allows us to easily implement something like a sorting
routine.
One of the simplest techniques for sorting is called a bubble sort
and is based on the following observations:
First we'll be making passes through the array comparing each
pair of consecutive elements, i.e. compare elements 0 and 1, then elements
1 and 2, then 2 and 3, and so on.
| If we compare elements | j and j+1,
and element j is bigger
than element j+1 we'll swap them.
(This is if we're sorting in ascending order; if we're sorting in descending
order, reverse the comparison.)
For each pass through the array, the biggest element will "bubble"
up to the top of the array.
\item So if we have n elements to sort, we need only do n passes
through the data each one going up to, but not including, the biggest
element sorted in the last pass.
| |
![]()
void bubble_sort( int a[], int num )
{
int i, j ;
for( i = num; i > 1; --i )
for( j = 0; j < i - 1; ++j )
if( a[j] > a[j+1] )
swap( &a[j], &a[j+1] ) ;
}
![]()
![]()
f1()
that takes a character array and an integer
as arguments and returns an integer.
The string parameter should be called s and the integer parameter
called n.
![]()