Write a C program to sort the digits of an integer in ascending and descending order using pointers.
Note:
Enter an integer
print the integer in ascending and descending order
For example:
Test Input Result
1 54387 34578
87543
#include <stdio.h>
int main()
{
int number, i, j, n, temp;
int digits [10];
int *p = digits;
printf("Enter number: ");
scanf("%d", &number);
n = 0;
while (number != 0)
{
*(p+n) = number % 10;
number = (int)(number / 10);
n++;
}
printf("\nRezult:\n");
for (i = 0; i < n-1; i++)
for(j = i+1; j < n; j++)
if (*(p+i) > *(p+j))
{
temp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = temp;
}
for (i = 0; i < n; i++)
printf("%d", *(p+i));
printf("\n");
for (i = 0; i < n-1; i++)
for(j = i+1; j < n; j++)
if (*(p+i) < *(p+j))
{
temp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = temp;
}
for (i = 0; i < n; i++)
printf("%d", *(p+i));
printf("\n");
}
Comments
Leave a comment