if और else
if और else program को यह चुनने देते हैं कि क्या करना है, जैसे 'अगर ठंड है तो कोट पहनो, नहीं तो t-shirt पहनो'। block सिर्फ तभी चलता है जब सवाल true हो।
In this page:
Syntax
if (condition) {
// body
} else if (other_condition) {
// body
} else {
// body
}
if / else
एक if statement सिर्फ तभी एक block चलाता है जब उसकी condition true हो, और एक optional else बाकी स्थितियों में चलता है, कई conditions के लिए else if के साथ chain करते हुए।
जैसा पहले कवर किया गया, if/else एक expression भी है जो एक value produce करता है। single statement के लिए braces optional हैं लेकिन multi-line blocks में स्पष्टता के लिए सुझाए जाते हैं।
Note:
multi-way branching के लिए अलग-अलग if blocks को nest करने के बजाय
else if से conditions को chain करें।उदाहरण: if / else
object Main extends App {
val score = 72
if (score >= 90) {
println("A")
} else if (score >= 70) {
println("B")
} else {
println("C")
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
else ifconditions को गलत क्रम में लिखना, जैसेscore >= 90से पहलेscore >= 70जांचना, जिससे पहली true branch बाद वाली को छुपा देती है।- condition में
==के बजाय=का उपयोग करना, जो compile नहीं होता। - पुराने Scala 2 code में
}के बाद नई line परelseडालना जहां यहifसे जुड़ न सके, जबकि} else {को एक ही line पर रखना सुरक्षित है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: