Passing Arrays to Functions

C Language

Write the definition of a function reverse, whose first parameter is an array of integers and whose second parameter is the number of elements in the array . The function reverses the elements of the array . The function does not return a value .


First Attempt:

1
2
3
4
5
6
7
8
void reverse (int a[], int n){
    int temp;
    for (int k=0; k<n/2; k++){
        temp=a[k];
        a[k]=a[n-k-1];
        a[n-k-1]=temp;
    }
}


Second Attempt:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void reverse(int *a, int b)
{
	for (int i = 0; i < b / 2; i++)
	{
		int t = a[i];
		a[i] = a[b - i - 1];
		a[b - i - 1] = t;
	}
} 
     
int main(void) {
	int numbers[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
	reverse(&numbers, 9);
	for (int i = 0; i < 9; i++)
		printf("%d, ", numbers[i]);
}

Last edited on
All 3 of those functions are identical. And I believe the algorithm is correct.
You didn't ask any questions, so Idk what else there is to say..
Topic archived. No new replies allowed.