The if keyword
The if keyword plays a vital role of a program logic. You use if and else keywords to design a decision structure so that you can change the path of execution or program flow for a specific condition.
if-then-else
You evaluate that if a condition is either true or false. The result of evaluation changes the course of a program.
Among the few decision structures provided by C# we will look at the if and else pattern of writing logic into our code.
Note: The condition must evaluate to either true or false.
In the if construct the condition is evaluated and if it evaluates to a value of true then the statement or a block of statements in the then part will be executed like so
The if keyword
Sample 1
-When you only want to check for truthyif(condition)
statement or block
if(condition)
{
statement or block
}else
{ statement or block
}
-When you want many alternatives if the condition is not truthy
if(condition)
{
statement or block
}
else if(condition)
{
statement or block
}
else
{
statement or block
}
Example 1
int a = 5;
int b = 2;
if ((a+b)==7){
Console.WriteLine("Yes a+b is 7");
}
Console.WriteLine("Hi I will be executed anyway");
}
else
{
statement or block
}
}
Example 2:
What if the condition evaluates to false? You may want to check for something else like so....
Code to check the names before passing the key. Only Alan or Sara can have the key..
string name = Console.ReadLine(); //user types "Alan"
if(name.Equals("Alan"))
{
Console.WriteLine("The name is Alan. Give him the key.");
{
Console.WriteLine("The name is Alan. Give him the key.");
}
else if(name.Equals("Sara"))
{
Console.WriteLine("The name is Sara. Give her the key.");
{
Console.WriteLine("The name is Sara. Give her the key.");
}
Example 3:
You can write nested if's and else's within an if or an else block.
int number = 56;
if(number > 100)
{
Console.WriteLine("The number is greater than 100");
}
else
{ if(number > 50)
{
Console.WriteLine("The number is greater than 50");
}
else
{ Console.WriteLine("The number is less than 50");
}}
Console.WriteLine("The number is greater than 100");
}}
No comments:
Post a Comment