Lesson 4.1

If Else Statements C# - With Programming Example


Objective

What is If Else Statement in C#?
How IF Else Statements Work?
Programming Example

What is IF ELSE Statement

If statements in c# identifies which block of code to run based on the result of Boolean expression (true or false). If the 'IF' statement not implemented, control goes to ELSE statements.

Example

If Else

According to picture example, if conditions return true the IF Block executed otherwise Else Block executed. Let’s understand it with a programming example.

We are writing a program in which we will ask age of the user and based on their age we will show message like that



ConditionMessage
If (age<=12)You are Kids
If (age>12 && age<=19)You are teenage.
ElseYou are adult
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if_else
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            Console.Write("Enter your age: ");
            age = Convert.ToInt32(Console.ReadLine());

            if (age <= 12)
            {
                Console.WriteLine("You are Kids");
            }

            else if (age > 12 && age <= 19)
            {
                Console.WriteLine("You are teenager");
            }

            else
            {
                Console.WriteLine("You are adult");
            }

            Console.ReadKey();
        }
    }
}

	

Output

Enter your age: 8
You are Kids

Enter your age: 15
You are teenager

Enter your age: 37
You are adult

__

Summary

In this chapter you have learned what 'If Else statement' is in C # and how to use it in programming language. In the next chapter you will learn about Nested IF statements.

BackNext