Breaking

Tuesday, April 16, 2019

Program no: 8(A) C program to insert 10 integer numbers in Array. Print the element of array in ascending order using pointer Method.

C program to insert 10 integer numbers in Array. Print the element of array in ascending order using pointer Method.

Write a C program to input elements in an array and sort array using pointers. How to sort an array in ascending or descending order using function pointers in C programming. Logic to sort an array using pointers in program.
Example
Input
Input array elements: 10 -1 0 4 2 100 15 20 24 -5
Output
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");
}


logic behind the C program
Below is the step by step descriptive logic to sort an array using pointer.
  1. Input size and elements in array. Store them in some variable say size and arr.
  2. Declare two function with prototype int sortAscending(int * num1, int * num2) and int sortDescending(int * num1, int * num2).
    Both the functions are used to compare two elements and arrange it in either ascending or descending order. sortAscending() returns negative value if num1 is less than num2, positive value if num1 is greater than num2and zero if both are equal.
    Similarly, sortDescending() returns negative value if num1 is greater than num2, positive value if num2 is greater than num1 and zero if both are equal.
  3. Declare another function to sort array with prototype void sort(int * arr, int size, int (* compare)(int *, int *)).
    It takes three parameter, where first parameter is the array to sort, second is size of array and third is a function pointer.
    Note: The function pointer passed here will decide relationship between two elements to be sorted. If you want to sort elements in ascending order then pass reference of sortAscending() function, otherwise sortDescending() function.
    To sort an array I have used basic sorting algorithm. The algorithm is not efficient when compared to other modern sorting algorithms but its easy to understand and use.

No comments:

Post a Comment

Popular Posts

Post Top Ad

Your Ad Spot

Pages