Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to find maximum of four integers by defining function
In C programming, we can find the maximum of four integers by defining our own function. We create a max() function that compares two numbers and returns the larger one, then use it repeatedly to find the maximum among all four numbers.
So, if the input is like a = 5, b = 8, c = 2, d = 3, then the output will be 8.
Syntax
int max(int x, int y);
Algorithm
To solve this, we will follow these steps −
- Define a function
max()that takes two integersxandy - Return the maximum of
xandy - Take four numbers
a,b,c, andd - Find
left_max = max(a, b) - Find
right_max = max(c, d) - Find
final_max = max(left_max, right_max) - Return or print the final maximum
Example
Let us see the following implementation to get better understanding −
#include <stdio.h>
int max(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
int main() {
int a = 5, b = 8, c = 2, d = 3;
int left_max = max(a, b);
int right_max = max(c, d);
int final_max = max(left_max, right_max);
printf("Numbers: a=%d, b=%d, c=%d, d=%d
", a, b, c, d);
printf("Maximum number is: %d
", final_max);
return 0;
}
Numbers: a=5, b=8, c=2, d=3 Maximum number is: 8
Alternative Approach: Single Function Call
We can also find the maximum in a single nested function call −
#include <stdio.h>
int max(int x, int y) {
return (x > y) ? x : y;
}
int main() {
int a = 10, b = 25, c = 15, d = 8;
int maximum = max(max(a, b), max(c, d));
printf("Numbers: a=%d, b=%d, c=%d, d=%d
", a, b, c, d);
printf("Maximum number is: %d
", maximum);
return 0;
}
Numbers: a=10, b=25, c=15, d=8 Maximum number is: 25
Key Points
- The
max()function can be reused for any number comparison - We can use the ternary operator
?:for a more concise comparison - The approach requires exactly 3 function calls to find maximum of 4 numbers
Conclusion
Using a user−defined max() function provides a clean and reusable solution to find the maximum of four integers. This modular approach makes the code more readable and maintainable.
Advertisements
