तीन संख्याओं में से सबसे बड़ी संख्या खोजने के लिए हम नेस्टेड if-else स्टेटमेंट्स का उपयोग करते हैं।
एल्गोरिदम
- पहली संख्या की तुलना दूसरी से करें।
- यदि पहली > दूसरी, तो पहली की तुलना तीसरी से करें।
- अन्यथा, दूसरी की तुलना तीसरी से करें।
पूर्ण उदाहरण
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int num1 = 10, num2 = 20, num3 = 50;
if (num1 > num2) {
if (num1 > num3) {
Console.Write("Number one is the largest!\n");
} else {
Console.Write("Number three is the largest!\n");
}
} else if (num2 > num3) {
Console.Write("Number two is the largest!\n");
} else {
Console.Write("Number three is the largest!\n");
}
}
}
}
आउटपुट
Number three is the largest!
बेहतर दृष्टिकोण: Math.Max का उपयोग
int max = Math.Max(num1, Math.Max(num2, num3));
Console.WriteLine("Maximum: " + max);
एक्सटेंशन: n संख्याओं में अधिकतम
int[] numbers = { 10, 20, 50, 5, 100, 30 };
int max = numbers.Max(); // LINQ का उपयोग
// या लूप के साथ
int max = numbers[0];
foreach (int n in numbers) {
if (n > max) max = n;
}
मुख्य बिंदु
- नेस्टेड if-else तर्क सरल लेकिन वर्बोज है।
Math.Maxदो संख्याओं की तुलना के लिए क्लीनर है।- सरणियों/कलेक्शन्स के लिए LINQ का
Max()सबसे सुविधाजनक है। - बराबर मानों के मामले में, पहली मिली अधिकतम संख्या लौटाई जाती है।