C program to find maximum between two numbers – In this article, we will discuss in on the several methods to find maximum between two numbers in C programming along with sample outputs.
Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.
The methods used in this piece are as follows:
- Using Standard Method
- Using Macros
- Using Function
As we are discussing in this blog, a maximum number between two numbers is decided based on their absolute value. The signs also matter since negative integers are smaller than positive integers.
Given in the photo above, you need to first enter two numbers.
In this case, the two numbers that have been entered are 25 and 40.
It is evident that 40 is greater than 25. Hence, 40 will be printed as the maximum number.
Thus, doing the same in C programming is as follows:
Using Standard Method
- Read the entered two numbers and store in the variables a,b.
2) If a>b then print “a is maximum number” otherwise print “b is the maximum number”.
1 2 3 4 5 6 7 8 9 10 11 |
#include<stdio.h> main() { int a,b; printf("Enter two numbers:\n"); scanf("%d%d",&a,&b); if(a>b) printf("%d is a maximum number\n",a); else printf("%d is a maximum number\n",b); } |
Output:
1 2 3 4 |
Enter two numbers: 25 40 40 is a maximum number |
Using Macros
- We are using macros concept. Here #define is the preprocessor. Max is defined as (a>b?a:b). So, In the program max(a,b) will replaced by (a>b?a:b).
2) So In the program max(a,b) will replaced by the conditional operator (a>b?a:b).
3) If a>b then it evaluates ‘a’ otherwise ‘b’.
1 2 3 4 5 6 7 8 9 |
#include<stdio.h> #define Max(a,b) (a>b?a:b) int main() { int a,b; printf("Enter two numbers:\n"); scanf("%d%d",&a,&b); printf("%d is maximum number\n",Max(a,b)); } |
Output:
1 2 3 4 |
Enter two numbers: 9 18 18 is maximum number |
Using Function
- The main() calls the maximum(int a, int b) function to find the maximum of two numbers.
2) The function maximum(int a,int b) returns ‘a’ if a>b.Otherwise, it returns ‘b’.
3) Store the returned value in the variable res. Print the res value which is the maximum of two numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<stdio.h> int maximum(int a,int b); main() { int n1,n2,res; printf("Enter two numbers:\n"); scanf("%d%d",&n1,&n2); res=maximum(n1,n2); printf("%d is a maximum number\n",res); } int maximum(int a,int b) { if(a>b) return a; else return b; } |
1 2 3 4 |
Enter two numbers: 54 45 54 is a maximum number |