Help creating a function

I'm reading a book and it's asking to try to make that piece of a code into a function. I have a grasp on function but I have no idea where to start. How can I condense all of this code into one function when it takes multiple functions to work in the first place. Any good logic tips are greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int findSmallestRemainingElement (int array[], int size, int index);
void swap (int array[], int first_index, int second_index);

void sort (int array[], int size)
{
	for ( int i = 0; i < size; i++ )
	{
		int index = findSmallestRemainingElement( array, size, i );
		swap( array, i, index );
	}
}

int findSmallestRemainingElement (int array[], int size, int index)
{
	int index_of_smallest_value = index;
	for (int i = index + 1; i < size; i++)
	{
		if ( array[ i ] < array[ index_of_smallest_value ]  )
		{
			index_of_smallest_value = i;
		}
	}
	return index_of_smallest_value;
}


void swap (int array[], int first_index, int second_index)
{
	int temp = array[ first_index ];
	array[ first_index ] = array[ second_index ];
	array[ second_index ] = temp;
}

// small helper method to display the before and after arrays
void displayArray (int array[], int size)
{
	cout << "{";
	for ( int i = 0; i < size; i++ )
	{
		// you'll see this pattern a lot for nicely formatting
		// lists--check if we're past the first element, and
		// if so, append a comma 
		if ( i != 0 )
		{
			cout << ", ";
		}
		cout << array[ i ];
	}
	cout << "}";
}

int main ()
{
	int array[ 10 ];
	srand( time( NULL ) ); 
	for ( int i = 0; i < 10; i++ )
	{
		// keep the numbers small so they're easy to read
		array[ i ] = rand() % 100;
	}
	cout << "Original array: ";
	displayArray( array, 10 );
	cout << '\n';

	sort( array, 10 );

	cout << "Sorted array: ";
	displayArray( array, 10 );
	cout << '\n';
}
Best to re-ask what they mean.

But here is a guess: main() calls sort() which uses findSmallestRemainingElement () and swap () to implement. Separate the three into a new file (say sort.cpp). Hide the two functions by making them static, leaving only sort() as a public symbol. At that point you need to link with the new file (sort.cpp) to get the original to link correctly. Once sort.cpp is separate, it can be used by any function, not just this one. Possibly this is what is being asked for.
Topic archived. No new replies allowed.