In many programming scenarios, you might need to determine the largest number among a set of values. This is a common problem and can be solved using conditional statements. In this article, we'll learn how to write a C# program to find the largest among three numbers.
Problem Statement: Write a C# program that finds the largest among three given numbers.
Example:
Input: num1 = 10, num2 =12, num3 = 7 Output: Largest Number = 12 Input: num1 = 8, num2 = -2, num3 = 5 Output: Largest Number = 8
C# Code to Find the Largest Number Among Three.
//C-sharp code to find largest among three numbers using System; namespace LargestNumberFinder { class Program { static void Main(string[] args) { Console.Write("Enter three numbers: "); int num1 = Convert.ToInt32(Console.ReadLine()); int num2 = Convert.ToInt32(Console.ReadLine()); int num3 = Convert.ToInt32(Console.ReadLine()); int largest = num1; if (num2 > largest) { largest = num2; } if (num3 > largest) { largest = num3; } Console.WriteLine($"Largest number among {num1}, {num2}, and {num3} is {largest}."); } } }
Enter three numbers: 10
23
9
Largest number among 10, 23, and 9 is 23.
Code Explanation:
- The program takes three integers as input using the Console.Write and Console.ReadLine functions.
- It initializes the largest variable with the value of the first input.
- Using a series of if statements, it compares the other two inputs with the largest variable and updates it if a larger value is found.
No comments:
Post a Comment