Program to find maximum using simple if
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
{
printf("%d is maximum", num1);
}
if(num2 > num1)
{
printf("%d is maximum", num2);
}
if(num1 == num2)
{
printf("Both are equal");
}
return 0;
}
The above approach to check maximum between two numbers is easy to understand. However, instead of writing three conditions you can use
if...else statement.
Program to find maximum between two numbers using if...else
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
{
printf("%d is maximum", num1);
}
else
{
printf("%d is maximum", num2);
}
return 0;
}
You can also use a max variable. Assign maximum in the max variable based on if...else
condition. Finally print the value of max.
In addition, as you can see in above programs if
or else
body contains only single statement. Hence, you can ignore braces {
}
after if
and else
statement.
Program to find maximum between two numbers
- /**
- * C program to find maximum between two numbers
- */
- #include <stdio.h>
- int main()
- {
- int num1, num2, max;
- /* Input two numbers from user */
- printf("Enter two numbers: ");
- scanf("%d%d", &num1, &num2);
- /* Compare num1 with num2 */
- if(num1 > num2)
- max = num1;
- else
- max = num2;
- printf("%d is maximum.", max);
- return 0;
- }