C program to find maximum between two numbers
C program to find maximum between two numbers
C program to input any two numbers from user and find maximum between two both numbrs using if...else and if...else-if. Let's see the below step by step logic to find the maximum between two numbers.
Before writing any program you just imagine about output screen first. Like what input to be given, and output to be displayed. Let's have a look at the below example.
- INPUT
- Enter any two number: 15, 30
OUTPUT
30 is maximum.
Required knowledge for this exercise
Logic to find maximum between two numbers:
In C programming, finding maximum or minimum between two numbers we need comparision of both numbers unig relational operator either >
or <
along with if...else
to find maximum. Relational operator evaluates either 1 (true
) or 0 (false
) depending on condition.
1) Input two numbers from user and store it in variables num1
or num2
using scanf()
2) Compare both numbersnum1
and num2
using below expression
if(num1 > num2)
.If it's true then print num1
is maximum.
else if(num2 > num1)
.If it's true then print num2
is maximum.
else
.If above both conditions are false then print both are equal.
Above expressions will return true(1) if condition is satisfied otherwise return false(0).
3)if(num1 > num2)
If it's true then printnum1
is maximum else print num2
is maximum.
Program to find maximum between two umbers using if...else-if:
-
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
{
printf("%d is maximum", num1);
}
else if (num2 > num1)
{
printf("%d is maximum", num2);
}
- else
{
printf("Both are equal");
}
return 0;
}
Program to find maximum between two umbers using if...else:
-
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
{
printf("%d is maximum", num1);
}
- else
{
printf("%d is maximum", num1);
}
return 0;
}
Above program can also be written as below with a little bit chages:
By storing maximum number in a max
variable and then print then resultant value.
-
#include <stdio.h>
int main()
{
int num1, num2, max;
printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);
if(num1 > num2)
max = num1;
- else
max = num2;
printf("%d is maximum", max);
return 0;
}
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.
Output:
- Enter any two number: 15, 30
- 30 is maximum
Help others by sharing this page.
Ahmad Irshad
Author & Editor
I love blogging, teaching, learning computer science and sharing it to others. I've written and develped this site so that students may learn computer science related tutorials eaisly. MCA / MCITP
Saturday, July 18, 2020
C
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.