C Program to find max of three numbers

C-Plus-Plus-Programs

In this post, we will learn C Program to find the max of three numbers using simple if statement, nested if-else statement, and using the conditional operator.

C Program to find max of three numbers using if statement


In this example, we asking the user to input three numbers. We are Using a Simple if statement to find the max of three numbers.

First checking if x >y and x>z if this condition is TRUE. The number x would be a max number.

Second checking if y >x and y>z if this condition is TRUE. The number y would be a max number.

Second checking if z >x and z>x if this condition is TRUE. The number z would be a max number.

C Program Example

#include<stdio.h>
int main()
{
 int x, y, z,max;

 printf("Please Enter x y z values\n");
 scanf("%d %d %d", &x, &y, &z);
 
  if (x >= y && x >= z)
        printf("%d is the max number.", x);

  if (y >= x && y >= z)
      printf("%d is the max number.", y);
  if (z >= x && z >= y)
      printf("%d is the max number.", z);
 return 0;
 
}

Output

Please Enter x y z values
13 45 200
200 is the max number.

C Program to find max of three numbers using if-else


In this example, we are using a nested if-else statement to find the max of three numbers.

First checking if x >y and x>z if this condition is TRUE. The number x would be a max number.

Second in the else-if statement we are checking if y >x and y>z if this condition is TRUE. The number y would be a max number.

In else-if we are checking if z >x and z>x if this condition is TRUE. The number z would be a max number.

The finally else statement if none of the given conditions is true.

C Program Example

#include <iostream>


int main()
{
 int x, y, z;

 printf("Please Enter x y z values\n");
 scanf("%d %d %d", &x, &y, &z);
 
 if (x > y && x > z) 
  {
   printf("\n%d is Greater Than  %d and %d", x, y, z); 
  }
 else if (y > x && y > z) 
  {
   printf("\n%d is Greater Than  %d and %d", y, x, z);
  }
 else if (z > x && z > y) 
  {
   printf("\n%d is Greater Than  %d and %d", z, x, y);
  }
 else 
  {
   printf("\n any two gieven values or all the three values are equal");
  } 
 return 0;
}

Output

Please Enter x y z values
13 14 15

15 is Greater Than  13 and 14

C find the largest of three number Using conditional operator


In this example, we are using condition operator (:) to find the max of three numbers. The conditional operator makes us write less and clean code.

C Program Example

#include<stdio.h>


int main()
{
 int x, y, z,max;

 printf("Please Enter x y z values\n");
 scanf("%d %d %d", &x, &y, &z);
 
 
 max =((x>y && x>z)?x: (y>z)?y:z);

 printf("\n Max number in all three number is: %d", max);
 return 0;
 
}

Output

Please Enter x y z values
56 90 100

 Max number in all three number is: 100

Summary


In this post, we learned C Program to find the max of three numbers using simple if statement, nested if-else statement, and using the conditional operator.