Arrays in functions

Hey all,

I just finished with my code to rearrange any given array and Im trying to clean up my code by putting it into a function. I just need a tip on how to create the beginning of the function.

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
  #include<iostream>

using namespace std;

//Precondition:  
//Postcondition:  
void arrange(int array[],);   //This is the part I need help with.
//Precondition:  
//Postcondition: 
//double area(int a, int b, int c);   //ignore as this is just an example from another program I made. 

int main()
{
	int array[10], i=0, temp, j=0;
	cout << "This program rearranges an array.\n";
	cout << "Please enter an array.\n";
	for (i=0; i < 10; i++)
	{
		cin >> array[i];
	}
	for (i = 0; i < 10; i++)  //I want to put this into a function. 
	{
		for (j = i + 1; j < 10; j++)
		{
			if (array[i]>array[j])
			{
				temp = array[i];
				array[i] = array[j];
				array[j] = temp;
			}
		}
	}
	cout << "The rearranged array is\n";
	for (i = 0; i < 10; i++)      //I want to put this into a function. 
	{
		cout << array[i] << " ";
	}
	return 0;
}
Last edited on
You can do that by

1
2
3
 void arrange(){
//place your code to rearrange the array here.
}


then in int main() you would call your function like so:
arrange();

Hope this helps.
Last edited on
get rid of the extraneous comma in your declaration, so instead of
void arrange(int array[],);
use
void arrange(int array[]);
Define the function and put the block you want in the function body.
You can either make your declaration into a definition, or define it elsewhere.
So, you could change line 7 to:
1
2
3
void arrange(int array[])
{
}

or add it afterwards so you have line 7:
[code]void arrange(int array[]);
[/code]
and line 41:
1
2
3
void arrange(int array[])
{
}

Place the indicated block in your function body, remembering to initialise the local variables:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void arrange(int array[])
        for (int i = 0; i < 10; i++) 
	{
		for (int j = i + 1; j < 10; j++)
		{
			if (array[i]>array[j])
			{
				temp = array[i];
				array[i] = array[j];
				array[j] = temp;
			}
		}
	}
}

Call it in main - line 21, like so:
arrange(array);
The array isn't passed by value, so the array you have in main() is what get's modified and you can pass it to your second function as well for display.
Update:

I got crammed doing a bunch of last minute programs because my professor is evil lol. I just got finished doing 3 programs in 2 days so it might be awhile before I church this thing up. Thanks for all the assist and Ill load it when its complete.
Topic archived. No new replies allowed.