Here's an example program in C that sorts N integer numbers in an array in descending order using pointers:
void sort(int *arr, int n);
int main() {
int n, i;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, n);
printf("\nSorted array in descending order:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void sort(int *arr, int n) {
int i, j, temp;
for(i = 0; i < n-1; i++) {
for(j = i+1; j < n; j++) {
if(*(arr+i) < *(arr+j)) {
temp = *(arr+i);
*(arr+i) = *(arr+j);
*(arr+j) = temp;
}
}
}
}
In this program, the sort function takes an array and its size as input arguments. It uses a nested loop to compare each pair of elements in the array and swaps them if they are in the wrong order (i.e., if the element on the left is less than the element on the right). The array is sorted in descending order since the elements are swapped if the left element is less than the right element. The main function prompts the user to input the size of the array and the integers to fill it with, then calls the sort function to sort the array in descending order. Finally, it prints the sorted array to the console.
Note that the function uses pointer arithmetic to access the elements of the array, using the syntax *(arr+i) to access the i-th element of the array. This is equivalent to arr[i], but using pointer arithmetic can make the code more concise and easier to read in some cases.
Comments
Post a Comment
If you have any doubts, please let me know