In this article, we will learn how we can write a C program to find maximum between two numbers.
The program takes two integer inputs from the user and prints the maximum of the two.
Sample Input:
Enter first number: 10
Enter second number: 20
Output:
20 is largest
You can follow the below steps to find the largest of the two numbers:
- Declare two integer variables
num1
&num2
and use thescanf()
function to take the inputs from the user. - Check if num1 > num2 , if yes, then num1 is the largest.
- Check if num1 < num2, if yes, then num2 is the largest.
- Check if num1 == num2, if yes, then both numbers are equal.
See the implementation in the following C program:
// C program to find the maximum of the two numbers #include <stdio.h> int main() { // Declare both variables int num1, num2; // Get the first number printf("Enter first number: "); scanf("%d", & num1); // Get the second number printf("Enter second number: "); scanf("%d", & num2); // Compare the two numbers if (num1 > num2) { printf("%d is largest", num1); } else if (num1 < num2) { printf("%d is largest", num2); } else { printf("Both numbers are equal"); } return 0; }
Output:
Enter first number: 10 Enter second number: 20 20 is largest
Code Explanation:
- The program first asks the user to enter the first number, the entered number is stored in the
num1
variable. - It then asks the user to enter the second number which is stored in the
num2
variable. - After both numbers are entered, the program checks if the first number i.e.
num1
is greater than the second numbernum2
using theif condition
. If yes, it prints the result. - If the first number
num1
is less than the second numbernum2
, then theelse if
block is executed. - If the first two conditions don’t match it means that both numbers are equal, therefore, the
else block
executes which prints that both numbers are equal.
Thanks for reading.