Google News
logo
C Program to find greatest of three numbers

Program to find largest number using if statement :

In this program, we are using if statement. The steps followed in this program are :

1. User is asked to enter three numbers one by one. The program store these numbers into three variables num1, num2 and num3 using scanf() function.

2. Program compares num1 to other two variables num2 & num3 and if num1 is grater than both of these numbers then print num1 is the largest number.

3. Similarly compares num2 with num1 & num3 and if greater print num2 is the largest number.

4. Similar to step 2 and 3, compare num3 with num1 and num2 and if greater print num3 is the largest number.
Program :
#include <stdio.h>

int main() {

  double num1, num2, num3;

  printf("Enter first number: ");
  scanf("%lf", &num1);
  printf("Enter second number: ");
  scanf("%lf", &num2);
  printf("Enter third number: ");
  scanf("%lf", &num3);

  // if num1 is greater than num2 & num3, num1 is the largest
  if (num1 >= num2 && num1 >= num3)
    printf("%lf is the largest number.", num1);

  // if num2 is greater than num1 & num3, num2 is the largest
  if (num2 >= num1 && num2 >= num3)
    printf("%lf is the largest number.", num2);

  // if num3 is greater than num1 & num2, num3 is the largest
  if (num3 >= num1 && num3 >= num2)
    printf("%lf is the largest number.", num3);

  return 0;
}
Output :
Enter first number: 2
Enter second number: 5
Enter third number: 7
7.000000 is the largest number.

Program to find largest number using if..else statement :

Program :
#include <stdio.h>
int main() {

  double num1, num2, num3;

  printf("Enter first number: ");
  scanf("%lf", &num1);
  printf("Enter second number: ");
  scanf("%lf", &num2);
  printf("Enter third number: ");
  scanf("%lf", &num3);

  if (num1 >= num2 && num1 >= num3)
    printf("%lf is the largest number.", num1);

  else if (num2 >= num1 && num2 >= num3)
    printf("%lf is the largest number.", num2);

  // if both the above conditions are false then
  // num3 is the largest number
  else
    printf("%lf is the largest number.", num3);

  return 0;
}
Output :
Enter first number: 24
Enter second number: 39
Enter third number: 18
39.000000 is the largest number.