Write a C program to input two or more numbers from user and find maximum and minimum of the given numbers using functions. How to find maximum and minimum of two or more numbers using functions in C programming.
Example
Input
Input two numbers: 10 20
Output
Maximum = 20 Minimum = 10
Required knowledge
Basic C programming, Functions, Returning value from function, Variable length arguments
Must know – Program to find maximum using conditional operator.
Declare function to find maximum
We already learned to find maximum using conditional operator and using many other approaches. Here, I will embed the logic to find maximum within a function. Let us define function to find maximum.
- First give a meaningful name to our function. Say
max()
function is used to find maximum between two numbers. - Second, we need to find maximum between two numbers. Hence, the function must accept two parameters of
int
type say,max(int num1, int num2)
. - Finally, the function should return maximum among given two numbers. Hence, the return type of the function must be same as parameters type i.e.
int
in our case.
After combining the above three points, function declaration to find maximum is int max(int num1, int num2);
.
Program to find maximum and minimum between two numbers using functions
Output
Enter any two numbers: 10 20 Maximum = 20 Minimum = 10
Note: You can also use variable argument list to find maximum or minimum between two or more variables at once.
Program to find maximum using var-args
Output
Maximum of three numbers: (10, 30, 20) = 30 Maximum of five numbers: (5, -45, 4, 60, 100) = 100 Minimum of four numbers: (-5, 0, 10, 50) = -5 Minimum of two numbers: (10, 20) = 10
Happy coding