C program to sort n numbers in ascending order using pointers
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j, n, tmp, *ptr;
/* get the number of inputs from the user */
printf("Enter number of inputs:");
scanf("%d", &n);
/* dynamic memory allocation for n elements */
ptr = (int *)malloc(sizeof(int) * n);
/* get the inputs from the user */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++) {
scanf("%d", ptr + i);
}
/* sort the given numbers in ascending order */
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (*(ptr + i) > *(ptr + j)) {
tmp = *(ptr + i);
*(ptr + i) = *(ptr + j);
*(ptr + j) = tmp;
}
}
}
/* prints the sorted numbers */
printf("Output:\n");
for (i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}
printf("\n");
/* release the dynamically allocated memory */
free(ptr);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter number of inputs: 5
Enter your inputs:
99 29 34 14 25
Output:
14 25 29 34 99
Enter number of inputs: 5
Enter your inputs:
99 29 34 14 25
Output:
14 25 29 34 99
Dell Laptop Repair Center in Noida is no.1 service center which provides door to door services in or its nearby areas. We have expert, technicians who can repair your laptop at your home. . Call us: 9891868324
ReplyDelete