Write a C program to sort numbers using pointers.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *data;
int i, j, n, temp;
/* get the number of inputs from the user */
printf("Enter the number of inputs:");
scanf("%d", &n);
/* dynamically allocate memory to store i/p data */
data = (int *)malloc(sizeof(int) * n);
/* get the input data from the user */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", (data + i));
}
/* sort the given data in ascending order */
for (i = 0; i < n - 1; i++) {
temp = *(data + i);
for (j = i + 1; j < n; j++) {
if (temp > *(data + j)) {
temp = *(data + j);
*(data + j) = *(data + i);
*(data + i) = temp;
}
}
}
#include <stdlib.h>
int main() {
int *data;
int i, j, n, temp;
/* get the number of inputs from the user */
printf("Enter the number of inputs:");
scanf("%d", &n);
/* dynamically allocate memory to store i/p data */
data = (int *)malloc(sizeof(int) * n);
/* get the input data from the user */
printf("Enter your inputs:\n");
for (i = 0; i < n; i++) {
printf("Data[%d]: ", i);
scanf("%d", (data + i));
}
/* sort the given data in ascending order */
for (i = 0; i < n - 1; i++) {
temp = *(data + i);
for (j = i + 1; j < n; j++) {
if (temp > *(data + j)) {
temp = *(data + j);
*(data + j) = *(data + i);
*(data + i) = temp;
}
}
}
printf("Data After Sorting:\n");
/* print the result */
for (i = 0; i < n; i++) {
printf("%d ", *(data + i));
}
printf("\n");
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of inputs:5
Enter your inputs:
Data[0]: 150
Data[1]: 110
Data[2]: 180
Data[3]: 120
Data[4]: 175
Data After Sorting:
110 120 150 175 180
Enter the number of inputs:5
Enter your inputs:
Data[0]: 150
Data[1]: 110
Data[2]: 180
Data[3]: 120
Data[4]: 175
Data After Sorting:
110 120 150 175 180
No comments:
Post a Comment