if / else
if and else let a program choose what to do, like 'if it is cold, wear a coat, else wear a t-shirt'. The code in a block runs only when its question is true.
In this page:
Syntax
if (condition1)
{
// ...
}
else if (condition2)
{
// ...
}
else
{
// none matched
}
if / else
An if statement runs a block only when its condition is true; an optional else runs when it's false. else if chains let you test multiple conditions in order, stopping at the first match.
Braces are optional for single statements but recommended for clarity.
Note:
Chain conditions with
else if instead of nesting separate if blocks.Example: if / else
using System;
class Program
{
static void Main(string[] args)
{
int score = 72;
if (score >= 90)
Console.WriteLine("A");
else if (score >= 70)
Console.WriteLine("B");
else
Console.WriteLine("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. #}
Common Mistakes
- Writing
if (x = 5)with a single equals sign, which is an assignment and only compiles when the assigned value is a bool. - Putting a semicolon after the condition,
if (x > 0);, so the body always runs. - Omitting braces so only the first statement after
ifbelongs to it.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: