0% found this document useful (0 votes)
324 views20 pages

Functions: C Program To Find Maximum and Minimum Using Functions

The document contains C program code snippets demonstrating the use of functions and pointers to perform common tasks like finding maximum/minimum, checking if a number is prime, calculating factorials, Fibonacci series, summing array elements, and more. Each code snippet is preceded by a brief description and includes main() function, other required functions, sample input/output. The code snippets serve as examples of applying functions and pointers in C programming to solve problems recursively and manipulate arrays and numbers.

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
324 views20 pages

Functions: C Program To Find Maximum and Minimum Using Functions

The document contains C program code snippets demonstrating the use of functions and pointers to perform common tasks like finding maximum/minimum, checking if a number is prime, calculating factorials, Fibonacci series, summing array elements, and more. Each code snippet is preceded by a brief description and includes main() function, other required functions, sample input/output. The code snippets serve as examples of applying functions and pointers in C programming to solve problems recursively and manipulate arrays and numbers.

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

FUNCTIONS

C program to find maximum and minimum using functions


#include <stdio.h>
/* Function declarations */
int max(int num1, int num2);
int min(int num1, int num2);

main()
{
int num1, num2, maximum, minimum;

/* Input two numbers from user */


printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);

maximum = max(num1, num2); // Call maximum function


minimum = min(num1, num2); // Call minimum function

printf("\nMaximum = %d\n", maximum);


printf("Minimum = %d", minimum);

getch();
}

/**
* Find maximum between two numbers.
*/
int max(int num1, int num2)
{
return (num1 > num2 ) ? num1 : num2;
}

/**
* Find minimum between two numbers.
*/
int min(int num1, int num2)
{
return (num1 > num2 ) ? num2 : num1;
}
Input two numbers: 10
20
Output
Maximum = 20
Minimum = 10

C program to find prime numbers in given range using functions


#include <stdio.h>

/* Function declarations */
int isPrime(int num);
void printPrimes(int lowerLimit, int upperLimit);

int main()
{
int lowerLimit, upperLimit;

printf("Enter the lower and upper limit to list primes: ");


scanf("%d%d", &lowerLimit, &upperLimit);

// Call function to print all primes between the given range.


printPrimes(lowerLimit, upperLimit);
return 0;
}

/**
* Print all prime numbers between lower limit and upper limit.
*/
void printPrimes(int lowerLimit, int upperLimit)
{
printf("All prime number between %d to %d are: ", lowerLimit, upperLimit);

while(lowerLimit <= upperLimit)


{
// Print if current number is prime.
if(isPrime(lowerLimit))
{
printf("%d, ", lowerLimit);
}

lowerLimit++;
}
}

/**
* Check whether a number is prime or not.
* Returns 1 if the number is prime otherwise 0.
*/
int isPrime(int num)
{
int i;

for(i=2; i<=num/2; i++)


{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if(num % i == 0)
{
return 0;
}
}

return 1;
}
Input
Input lower limit: 10
Input upper limit: 50
Output
Prime numbers between 10-50 are: 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
C program to print all strong numbers between given interval using function
#include <stdio.h>

/* Function declaration */
long long fact(int num);
void printStrongNumbers(int start, int end);

int main()
{
int start, end;

/* Input start and end range */


printf("Enter the lower limit to find strong number: ");
scanf("%d", &start);
printf("Enter the upper limit to find strong number: ");
scanf("%d", &end);

printf("All strong numbers between %d to %d are: \n", start, end);


printStrongNumbers(start, end);

return 0;
}

/**
* Print all strong numbers in a given range
*/
void printStrongNumbers(int start, int end)
{
long long sum;
int num;

// Iterates from start to end


while(start != end)
{
sum = 0;
num = start;

// Calculate sum of factorial of digits


while(num != 0)
{
sum += fact(num % 10);
num /= 10;
}

// If sum of factorial of digits equal to current number


if(start == sum)
{
printf("%d, ", start);
}

start++;
}
}

/**
* Recursively find factorial of any number
*/
long long fact(int num)
{
if(num == 0)
return 1;
else
return (num * fact(num-1));
}
Input
Input lower limit: 1
Input upper limit: 1000
Output
Strong numbers between 1 to 100: 1, 2, 145
C program to find sum of digits using recursion
#include <stdio.h>

/* Function declaration */
int sumOfDigits(int num);

int main()
{
int num, sum;

printf("Enter any number to find sum of digits: ");


scanf("%d", &num);

sum = sumOfDigits(num);

printf("Sum of digits of %d = %d", num, sum);

return 0;
}

/**
* Recursive function to find sum of digits of a number
*/
int sumOfDigits(int num)
{
// Base condition
if(num == 0)
return 0;

return ((num % 10) + sumOfDigits(num / 10));


}
Input
Input number: 1234
Output
Sum of digits: 10
C program to find factorial of a number using recursion
#include <stdio.h>

/* Function declaration */
unsigned long long fact(int num);

int main()
{
int num;
unsigned long long factorial;

/* Input an integer from user */


printf("Enter any number: ");
scanf("%d", &num);

factorial = fact(num); // Call factorial function

printf("Factorial of %d is %llu", num, factorial);

return 0;
}

/**
* Function to compute and return factorial of any number recursively.
*/
unsigned long long fact(int num)
{
// Base condition
if(num == 0)
return 1;
else
return num * fact(num - 1);
}
Input
Input any number: 5
Output
Factorial of 5 = 120
C program to generate nth fibonacci term using recursion
#include <stdio.h>

/* Function declaration */
unsigned long long fibo(int num);

int main()
{
int num;
unsigned long long fibonacci;

/* Input a number from user */


printf("Enter any number to find nth fiboacci term: ");
scanf("%d", &num);

fibonacci = fibo(num);

printf("%d fibonacci term is %llu", num, fibonacci);

return 0;
}

/**
* Recursive function to find nth Fibonacci term
*/
unsigned long long fibo(int num)
{
if(num == 0) //Base condition
return 0;
else if(num == 1) //Base condition
return 1;
else
return fibo(num-1) + fibo(num-2);
}
Input
Input any number: 10
Output
10th Fibonacci term: 55
C program to print elements of array using recursion
#include <stdio.h>
#define MAX_SIZE 100

/* Function declaration */
void printArray(int arr[], int start, int len);

int main()
{
int arr[MAX_SIZE];
int N, i;

/* Input size and elements in array */


printf("Enter size of the array: ");
scanf("%d", &N);
printf("Enter elements in the array: ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}

/* Prints array recursively */


printf("Elements in the array: ");
printArray(arr, 0, N);

return 0;
}

/**
* Prints an array recursively within a given range.
*/
void printArray(int arr[], int start, int len)
{
/* Recursion base condition */
if(start >= len)
return;

/* Prints the current array element */


printf("%d, ", arr[start]);

/* Recursively call printArray to print next element in the array */


printArray(arr, start + 1, len);
}
Input
Input size: 10
Input elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Output
Array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
C program to find sum of array elements using recursion
#include <stdio.h>
#define MAX_SIZE 100

/* Function declaration to find sum of array */


int sum(int arr[], int start, int len);

int main()
{
int arr[MAX_SIZE];
int N, i, sumofarray;

/* Input size and elements in array */


printf("Enter size of the array: ");
scanf("%d", &N);
printf("Enter elements in the array: ");
for(i=0; i<N; i++)
{
scanf("%d", &arr[i]);
}

sumofarray = sum(arr, 0, N);


printf("Sum of array elements: %d", sumofarray);

return 0;
}

/**
* Recursively find the sum of elements in an array.
*/
int sum(int arr[], int start, int len)
{
/* Recursion base condition */
if(start >= len)
return 0;
return (arr[start] + sum(arr, start + 1, len));
}
Input
Input size of array: 10
Input array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Output
Sum of array: 55

C program to add two numbers using pointers


#include <stdio.h>

int main()
{
int num1, num2, sum;
int *ptr1, *ptr2;

ptr1 = &num1; // ptr1 stores the address of num1


ptr2 = &num2; // ptr2 stores the address of num2

printf("Enter any two numbers: ");


scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

printf("Sum = %d", sum);

return 0;
}
Input
Input num1: 10
Input num2: 20
Output
Sum = 30
Difference = -10
Product = 200
Quotient = 0
Program to perform all arithmetic operations using pointers
#include <stdio.h>

int main()
{
float num1, num2; // Normal variables
float *ptr1, *ptr2; // Pointer variables

float sum, diff, mult, div;

ptr1 = &num1; // ptr1 stores the address of num1


ptr2 = &num2; // ptr2 stores the address of num2

/* User input through pointer */


printf("Enter any two real numbers: ");
scanf("%f%f", ptr1, ptr2);

/* Perform arithmetic operation */


sum = (*ptr1) + (*ptr2);
diff = (*ptr1) - (*ptr2);
mult = (*ptr1) * (*ptr2);
div = (*ptr1) / (*ptr2);

/* Print the results */


printf("Sum = %.2f\n", sum);
printf("Difference = %.2f\n", diff);
printf("Product = %.2f\n", mult);
printf("Quotient = %.2f\n", div);

return 0;
}
C program to input and print array elements using pointers
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size

int main()
{
int arr[MAX_SIZE];
int N, i;
int * ptr = arr; // Pointer to arr[0]

printf("Enter size of array: ");


scanf("%d", &N);

printf("Enter elements in array:\n");


for (i = 0; i < N; i++)
{
scanf("%d", ptr);

// Move pointer to next array element


ptr++;
}

// Make sure that pointer again points back to first array element
ptr = arr;

printf("Array elements: ");


for (i = 0; i < N; i++)
{
// Print value pointed by the pointer
printf("%d, ", *ptr);

// Move pointer to next array element


ptr++;
}

return 0;
}
Input
Input array size: 10
Input elements: 1
2
3
4
5
6
7
8
9
10
Output
Array elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
C program to reverse an array using pointers
#include <stdio.h>

#define MAX_SIZE 100

/* Function declaration */
void printArr(int *arr, int size);

int main()
{
int arr[MAX_SIZE];
int size;
int *left = arr; // Pointer to arr[0]
int *right;

// Input size of array


printf("Enter size of array: ");
scanf("%d", &size);

right = &arr[size - 1]; // Pointer to arr[size - 1]

/*
* Input elements in array
*/
printf("Enter elements in array: ");
while(left <= right)
{
scanf("%d", left++);
}

printf("\nArray before reverse: ");


printArr(arr, size);

// Make sure that left points to arr[0]


left = arr;

// Loop to reverse array


while(left <= right)
{
/*
* Swap element from left of array to right of array.
*/
*left ^= *right;
*right ^= *left;
*left ^= *right;

// Increment left array pointer and decrement right array pointer


left++;
right--;
}

printf("\nArray after reverse: ");


printArr(arr, size);

return 0;
}

/**
* Function to print array using pointer.
*
* @arr Pointer to array.
* @size Size of the array.
*/
void printArr(int * arr, int size)
{
// Pointer to arr[size - 1]
int * arrEnd = (arr + size - 1);

/* Loop till last array element */


while(arr <= arrEnd)
{
printf("%d, ", *arr);

// Move pointer to next array element.


arr++;
}
}
Input
Input array elements: 10 20 30 40 50 60 70 80 90 100
Output
Reversed array: 100 90 80 70 60 50 40 30 20 10
C program to search element in array using pointers
#include <stdio.h>

#define MAX_SIZE 100

/* Function declaration */
void inputArray(int * arr, int size);
int search(int * arr, int size, int toSearch);

int main()
{
int array[MAX_SIZE];
int size, toSearch, searchIndex;

/*
* Input size and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);

printf("Enter elements in array: ");


inputArray(array, size);

// Input element to search from user


printf("Enter element to search: ");
scanf("%d", &toSearch);

// Call search funtion to search element in array


searchIndex = search(array, size, toSearch);

// Print search results


if(searchIndex == -1)
printf("%d does not exists in array.", toSearch);
else
printf("%d is found at %d position.", toSearch, searchIndex + 1);

return 0;
}

/**
* Function to input elements in array.
*
* @arr Pointer to integer array
* @size Size of the array
*/
void inputArray(int * arr, int size)
{
// Pointer to last array element arr[0]
int * arrEnd = (arr + size - 1);

// Run loop till last array element


while(arr <= arrEnd)
{
scanf("%d", arr++);
}
}

/**
* Function to perform linear search in array. The function
* returns an integer between 0 to size-1 specifying first
* index of successful searched element in array.
*
* @arr Pointer to integer array.
* @size Size of the array.
* @toSearch Element to search within array.
*
* @return Returns -1 if element does not exists in array,
* otherwise returns element index.
*/
int search(int * arr, int size, int toSearch)
{
int index = 0;

// Pointer to last array element arr[size - 1]


int * arrEnd = (arr + size - 1);

/*
* Run a loop from start of array to last array element (arr <= arrEnd),
* until current array element does not match element to search.
*/
while(arr <= arrEnd && *arr != toSearch) {
arr++;
index++;
}

// If element is found
if(arr <= arrEnd)
return index;

return -1;
}
Input
Input array elements: 10 20 30 40 50 60 70 80 90 100
Input element to search: 25
Output
25 does not exists in array.
How to access two dimensional array using pointers in C programming?
#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration to input and print two dimensional array */


void inputMatrix(int matrix[][COLS], int rows, int cols);
void printMatrix(int matrix[][COLS], int rows, int cols);

int main()
{
int matrix[ROWS][COLS];
int i, j;

/* Input elements in matrix */


printf("Enter elements in %dx%d matrix.\n", ROWS, COLS);
inputMatrix(matrix, ROWS, COLS);

/* Print elements in matrix */


printf("Elements of %dx%d matrix.\n", ROWS, COLS);
printMatrix(matrix, ROWS, COLS);

return 0;
}

/**
* Function to take input in two dimensional array (matrix)
* from user.
*
* @matrix 2D array to store input.
* @rows Total rows in 2D matrix.
* @cols Total columns in 2D matrix.
*/
void inputMatrix(int matrix[][COLS], int rows, int cols)
{
int i, j;

for(i = 0; i < rows; i++)


{
for(j = 0; j < cols; j++)
{
// (*(matrix + i) + j is equivalent to &matrix[i][j]
scanf("%d", (*(matrix + i) + j));
}
}
}

/**
* Function to display elements of two dimensional array (matrix)
* on console.
*
* @matrix 2D array to display as output.
* @rows Total rows in 2D matrix.
* @cols Total columns in 2D matrix.
*/
void printMatrix(int (*matrix)[COLS], int rows, int cols)
{
int i, j;

for (i = 0; i < rows; i++)


{
for (j = 0; j < cols; j++)
{
// *(*(matrix + i) + j) is equivalent to matrix[i][j]
printf("%d ", *(*(matrix + i) + j));
}

printf("\n");
}
}

Input
Input elements in 3x3 matrix:
123
456
789
Output
Elements of 3x3 matrix:
123
456
789
C program to add two matrix using pointers
#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration to input, add and print matrix */


void matrixInput(int mat[][COLS]);
void matrixPrint(int mat[][COLS]);
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);

int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];

// Input elements in first matrix


printf("Enter elements in first matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat1);

// Input element in second matrix


printf("\nEnter elemetns in second matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat2);

// Finc sum of both matrices and print result


matrixAdd(mat1, mat2, res);

printf("\nSum of first and second matrix: \n");


matrixPrint(res);

return 0;
}

/**
* Function to read input from user and store in matrix.
*
* @mat Two dimensional integer array to store input.
*/
void matrixInput(int mat[][COLS])
{
int i, j;

for (i = 0; i < ROWS; i++)


{
for (j = 0; j < COLS; j++)
{
// (*(mat + i) + j) is equal to &mat[i][j]
scanf("%d", (*(mat + i) + j));
}
}
}

/**
* Function to print elements of matrix on console.
*
* @mat Two dimensional integer array to print.
*/
void matrixPrint(int mat[][COLS])
{
int i, j;

for (i = 0; i < ROWS; i++)


{
for (j = 0; j < COLS; j++)
{
// *(*(mat + i) + j) is equal to mat[i][j]
printf("%d ", *(*(mat + i) + j));
}
printf("\n");
}
}

/**
* Function to add two matrices and store their result in given res
* matrix.
*
* @mat1 First matrix to add.
* @mat2 Second matrix to add.
* @res Resultant matrix to store sum of mat1 and mat2.
*/
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS])
{
int i, j;

// Iterate over each matrix elements


for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// res[i][j] = mat1[i][j] + mat2[i][j]
*(*(res + i) + j) = *(*(mat1 + i) + j) + *(*(mat2 + i) + j);
}
}
}
Input
Input matrix1:
123
456
789
Input matrix2:
987
654
321
Output
Sum of both matrices:
10 10 10
10 10 10
10 10 10
C program to multiply two matrix using pointers
#include <stdio.h>

#define ROW 3
#define COL 3

/* Function declarations */
void matrixInput(int mat[][COL]);
void matrixPrint(int mat[][COL]);
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);

int main()
{
int mat1[ROW][COL];
int mat2[ROW][COL];
int product[ROW][COL];
/*
* Input elements in matrices.
*/
printf("Enter elements in first matrix of size %dx%d\n", ROW, COL);
matrixInput(mat1);

printf("Enter elements in second matrix of size %dx%d\n", ROW, COL);


matrixInput(mat2);

// Call function to multiply both matrices


matrixMultiply(mat1, mat2, product);

// Print product of both matrix


printf("Product of both matrices is : \n");
matrixPrint(product);

return 0;
}

/**
* Function to input elements in matrix from user.
*
* @mat Two-dimensional array to store user input.
*/
void matrixInput(int mat[][COL])
{
int row, col;

for (row = 0; row < ROW; row++)


{
for (col = 0; col < COL; col++)
{
scanf("%d", (*(mat + row) + col));
}
}
}

/**
* Function to print elements in a two-dimensional array.
*
* @mat Two-dimensional array to print.
*/
void matrixPrint(int mat[][COL])
{
int row, col;

for (row = 0; row < ROW; row++)


{
for (col = 0; col < COL; col++)
{
printf("%d ", *(*(mat + row) + col));
}

printf("\n");
}
}

/**
* Function to multiply two matrices.
*
* @mat1 First matrix
* @mat2 Second matrix
* @res Resultant matrix to store product of both matrices.
*/
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL])
{
int row, col, i;
int sum;

for (row = 0; row < ROW; row++)


{
for (col = 0; col < COL; col++)
{
sum = 0;

/*
* Find sum of product of each elements of
* rows of first matrix and columns of second
* matrix.
*/
for (i = 0; i < COL; i++)
{
sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));
}

/*
* Store sum of product of row of first matrix
* and column of second matrix to resultant matrix.
*/
*(*(res + row) + col) = sum;
}
}
}
Input
Input elements of matrix1:
10 20 30
40 50 60
70 80 90
Input elements of matrix2:
123
456
789
Output
Product of matrices is :
300 360 420
660 810 960
1020 1260 1500
C program to find length of a string
#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the string

int main()
{
char text[MAX_SIZE]; /* Declares a string of size 100 */
char * str = text; /* Declare pointer that points to text */
int count = 0;

/* Input string from user */


printf("Enter any string: ");
gets(text);

/* Iterate though last element of the string */


while(*(str++) != '\0') count++;

printf("Length of '%s' = %d", text, count);


return 0;
}
Input
Input string: I love programming. I love Codeforwin.
Output
Length of string: 38
Program to compare two strings using pointers
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Compare function declaration */


int compare(char * str1, char * str2);

int main()
{
char str1[MAX_SIZE], str2[MAX_SIZE];
int res;

/* Input two strings from user */


printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

/* Call the compare function to compare strings */


res = compare(str1, str2);

if(res == 0)
{
printf("Both strings are equal.");
}
else if(res < 0)
{
printf("First string is lexicographically smaller than second.");
}
else
{
printf("First string is lexicographically greater than second.");
}

return 0;
}

/**
* Compares two strings lexicographically.
*/
int compare(char * str1, char * str2)
{
while((*str1 && *str2) && (*str1 == *str2)) { str1++; str2++; }

return *str1 - *str2;


}
Program to find reverse of a string using pointers
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
char str[MAX_SIZE], reverse[MAX_SIZE];
char *s = str;
char *r = reverse;
int len = 0;

/* Input string from user */


printf("Enter any string: ");
gets(str);

/* Find length of string */


while(*(s++)) len++;

/*
* Store each character from end of original string
* to reverse string
*/
s--;
while(len >= 0)
{
*(r++) = *(--s);
len--;
}
*r = '\0';

printf("\nOriginal string = %s\n", str);


printf("Reverse string = %s", reverse);

return 0;
}
C program to sort an array using pointers
#include <stdio.h>

#define MAX_SIZE 100

/* Function declaration */
void inputArray(int * arr, int size);
void printArray(int * arr, int size);

/* Sort function declaration */


int sortAscending(int * num1, int * num2);
int sortDescending(int * num1, int * num2);

void sort(int * arr, int size, int (* compare)(int *, int *));

int main()
{
int arr[MAX_SIZE];
int size;

/*
* Input array size and elements.
*/
printf("Enter array size: ");
scanf("%d", &size);
printf("Enter elements in array: ");
inputArray(arr, size);

printf("\n\nElements before sorting: ");


printArray(arr, size);

// Sort and print sorted array in ascending order.


printf("\n\nArray in ascending order: ");
sort(arr, size, sortAscending);
printArray(arr, size);

// Sort and print sorted array in descending order.


printf("\nArray in descending order: ");
sort(arr, size, sortDescending);
printArray(arr, size);
return 0;
}

/**
* Function to take input in array elements.
*
* @arr Array to store input.
* @size Size of the array.
*/
void inputArray(int * arr, int size)
{
// Pointer to last element of array
int * arrEnd = (arr + size - 1);

// (arr++) Input in current array element and move to next element.


// Till last array element (arr <= arrEnd)
while(arr <= arrEnd)
scanf("%d", arr++);
}

/**
* Function to print all array elements.
*
* @arr Array to print.
* @size Size of the array.
*/
void printArray(int * arr, int size)
{
// Pointer to last element of array
int * arrEnd = (arr + size - 1);

// *(arr++) Print current array element and move to next element.


// Till last array element (arr <= arrEnd)
while(arr <= arrEnd)
printf("%d, ", *(arr++));
}

/**
* Function to compare two succesive elements.
* The function returns difference of first and second integer.
*
* @num1 First integer to compare.
* @num2 Second integer to compare.
*
* @return Difference of num1 and num2.
*/
int sortAscending(int * num1, int * num2)
{
return (*num1) - (*num2);
}

/**
* Function to compare two successive elements.
* The function returns difference of second and first parameter.
*
* @num1 First integer to compare.
* @num2 Second integer to compare.
*
* @return Difference of num2 and num1.
*/
int sortDescending(int * num1, int * num2)
{
return (*num2) - (*num1);
}

/**
* Function to sort an array in ascending or descending order.
* This function is used to sort array in both order ascending or
* descending.
*
* @arr Array to sort.
* @size Size of the array.
* @compare Function pointer returning integer and takes two int *
* parameter. The function is called to get arrangement of
* two successive array elements.
*/
void sort(int * arr, int size, int (* compare)(int *, int *))
{
// Pointer to last array element
int * arrEnd = (arr + size - 1);

// Pointer to current array element


int * curElem = arr;
int * elemToSort;

// Iterate over each array element


while(curElem <= arrEnd)
{
elemToSort = curElem;

// Compare each successive elements with current element


// for proper order.
while(elemToSort <= arrEnd)
{
/*
* Compare if elements are arranged in order
* or not. If elements are not arranged in order
* then swap them.
*/
if(compare(curElem, elemToSort) > 0)
{
*curElem ^= *elemToSort;
*elemToSort ^= *curElem;
*curElem ^= *elemToSort;
}

elemToSort++;
}

// Move current element to next element in array.


curElem++;
}
}
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,

You might also like