C program to insert 10 integer numbers in Array. Print the element of array in ascending order using pointer Method.
Input array elements: 10 -1 0 4 2 100 15 20 24 -5
Array in ascending order: -5, -1, 0, 2, 4, 10, 15, 20, 24, 100, Array in descending order: 100, 24, 20, 15, 10, 4, 2, 0, -1, -5,
Source code:
#include <stdio.h>
void main()
{
int a[100],i,n,j,t;
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter array:\n");
for (i=0; i<n; i++)
{
scanf("%d",a+i);
}
for (i=0; i<(n-1); i++)
{
for (j=i+1; i<n; i++)
{
if (*(a+i)>*(a+j))
{
t=*(a+i);
*(a+i)=*(a+j);
*(a+j)=t;
}
}
}
printf("Sorted array (ascending) is:\n");
for (i=0; i<n; i++)
{
printf("%d ",*(a+i));
}
printf("\n");
}
#include <stdio.h>
void main()
{
int a[100],i,n,j,t;
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter array:\n");
for (i=0; i<n; i++)
{
scanf("%d",a+i);
}
for (i=0; i<(n-1); i++)
{
for (j=i+1; i<n; i++)
{
if (*(a+i)>*(a+j))
{
t=*(a+i);
*(a+i)=*(a+j);
*(a+j)=t;
}
}
}
printf("Sorted array (ascending) is:\n");
for (i=0; i<n; i++)
{
printf("%d ",*(a+i));
}
printf("\n");
}
logic behind the C program
Below is the step by step descriptive logic to sort an array using pointer.
- Input size and elements in array. Store them in some variable say
size
andarr
. - Declare two function with prototype
int sortAscending(int * num1, int * num2)
andint sortDescending(int * num1, int * num2)
. - Declare another function to sort array with prototype
void sort(int * arr, int size, int (* compare)(int *, int *))
.
No comments:
Post a Comment