In this article, we'll explore using the ternary operator to find the maximum of three numbers in a C# program.
Problem Statement: Using ternary operators, write a C# program to find the maximum among three given numbers.
Example:
Input: num1 = 11, num2 =12, num3 = 7 Output: Largest Number = 12 Input: num1 = 4, num2 = -2, num3 = 5 Output: Largest Number = 5
Let's understand Ternary Operators before moving to the coding part to find the largest number among the three.
What are Ternary Operators?
The ternary operator, also known as the conditional operator, is a concise way to express simple conditional statements in programming languages like C#. It provides a compact syntax to perform an operation based on a condition.
The general syntax of the ternary operator is:
condition ? expression_if_true : expression_if_false
Here's a breakdown of how the ternary operator works:
- The condition is an expression that evaluates to either true or false.
- If the condition is true, the value of expression_if_true is returned.
- If the condition is false, the value of expression_if_false is returned.
I hope you get a basic idea of how Ternary operators work. Now let's use them to find the largest number.
C# Code to Find a Maximum of Three Numbers using Ternary Operators.
using System; namespace MaximumOfThreeNumbers { class Program { static void Main(string[] args) { Console.Write("Enter the first number: "); int num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the second number: "); int num2 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the third number: "); int num3 = Convert.ToInt32(Console.ReadLine()); int max = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3); Console.WriteLine($"The maximum number is: {max}"); } } }
Enter the first number: 20
Enter the second number: 10
Enter the third number: 9
The maximum number is: 20
Ternary operators offer a concise way to perform conditional operations and are especially useful when comparing multiple values.
Similar articles:
No comments:
Post a Comment