C program to find maximum between two numbers

Write a C program to find maximum between two numbers using if else. C program to enter two numbers from user and find maximum between two numbers using if else. How to find maximum or minimum between two numbers using if else in C programming.

Example
Input

Input num1: 10
Input num2: 20

Output

Maximum = 20

Required knowledge

Basic C programming, Use of Relational operators, If else

Logic to find maximum or minimum

Before we get on to this program, basic knowledge of if else and relational operator is needed. What we have learnt till now is if else statements work with true or false values. If the condition is true the if block is executed otherwise else get executed. In the series of learning we also learnt that there is a set of relational operators that evaluates to true or false values. That's all we need for this program.

Now, if I ask question to you. How will you manually check maximum between two numbers? The answer is simple, by looking both numbers and comparing them either by num1 > num2 or num1 < num2. The given two expressions in mathematics means that num1 is greater than num2; and num1 is less than num2 respectively. Now for C programming language, since num1 and num2 both are variables hence values will be determined during the execution of program. So is the truthness will be determined at runtime. Which means num1 > num2 will evaluate to true iff num1 is greater than num2 otherwise evaluate to false.

Let us now implement our logic.

Program to find maximum or minimum

/**
 * C program to find maximum between two numbers
 */

#include <stdio.h>

int main()
{
    int num1, num2;

    /*
     * Input two integer values from user
     */
    printf("Enter two numbers: ");
    scanf("%d%d", &num1, &num2);

    /*
     * Compare num1 with num2
     */
    if(num1 > num2)
    {
        // True part means num1 > num2
        printf("%d is maximum", num1);        
    }
    else
    {
        // False part means num1 < num2
        printf("%d is maximum", num2);
    }

    return 0;
}

Important Note: If you want to find minimum between two numbers. You only need to reverse the sign of if statement i.e. you can write it as if(num1 < num2) for checking minimum.

Before you move on to next program or exercise. Advance your programming skills by learning this program using other approaches.

Output

Enter two numbers: 10
12
12 is maximum

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>