C Program to Find Largest of Three Numbers Using Conditional Operator

Howdy readers, today you will learn how to write a program to find the largest of three numbers using the conditional operator in C Programming language.

C Program to Find Largest of Three Numbers Using Conditional Operator

The conditional operator is also known as ternary operator. The conditional statements are the decision making statements which depend upon the output of the expression. It is represented by two symbols ? and : .

Ternary operator takes three arguments:

  1. Condition
  2. Value to return when condition is True
  3. Value to return when condition is False

We will be using the above logic in this program to find the largest of three numbers.

So, without any delay, let’s begin this tutorial.

C Program to Find Largest of Three Numbers Using Conditional Operator

C Program

// C Program to Find Largest of Three Numbers Using Conditional Operator
#include <stdio.h>
int main(){
    int num1, num2, num3, largest;
    
    // Asking for input
    printf("Enter the first number: ");
    scanf("%d", &num1);
    printf("Enter the second number: ");
    scanf("%d", &num2);
    printf("Enter the third number: ");
    scanf("%d", &num3);
    
    // Finding largest number using ternary operator
    largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
    
    // Displaying output
    printf("%d is the largest number.", largest);
    
    return 0;
}

Output

Enter the first number: 28
Enter the second number: 65
Enter the third number: 40
65 is the largest number.
C Program to Find Largest of Three Numbers Using Conditional Operator

Explanation

    int num1, num2, num3, largest;

In this program, we have declared four int data type variables named num1, num2, num3 and largest.

    // Asking for input
    printf("Enter the first number: ");
    scanf("%d", &num1);
    printf("Enter the second number: ");
    scanf("%d", &num2);
    printf("Enter the third number: ");
    scanf("%d", &num3);

Then, the user is asked to enter three numbers.

    largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);

We find the largest numbers with the help of ternary operator. The largest of three numbers gets stored in the largest named variable.

    printf("%d is the largest number.", largest);

Finally, the largest of the three numbers is displayed on the screen using printf() function.

Conclusion

I hope after reading this post, you understand how to write a program to find the largest of three numbers using the conditional operator in C Programming language.

If you find any difficulty while understanding this program, then let us know in the comment section. We will be delighted to solve your query.

Also Read:

Leave a Comment