Decision Making Statements – If else statement

October18, 2017
by admin

Syntax:


  if(<conditional expression>)
  {
    // statement or statements to be executed
    // when conditional expression returns 
    // true
  }
  else
  {
    // statement or statements to be executed
    // when conditional expression returns 
    // false
  }

Ex:

Problem:

Write a program to show the output displaying if the user is passed in the examination or failed. Passing marks are 40.

Solution:


  int marks = 35;

  System.Console.WriteLine("Marks obtained in the exam: " + marks);

  if(marks >= 40)
  {
    System.Console.WriteLine("You passed in the examination");
  }
  else
  {
    System.Console.WriteLine("Sorry... You failed in the examination");
  }

Output:

Marks obtained in the exam: 35
You failed in the examination

The above code sample is displaying the output based on student’s marks obtained in the exam. The minimum marks for passing are 40. In both cases (either student passed or failed), we are displaying the appropriate message to the user. Let’s understand the code line by line.

In the first line, we have declared variable named marks having data type ‘int’ and initialized it with hard coded value, 35.

On the next line, we have displayed the statement showing the marks obtained in the exam to the output.

On the next line, we have used ‘if…else’ statement. We have checked the boolean condition in if statement to check whether marks are greater than 40 (including 40). If this condition returns true then we are displaying the message ’You passed the examination’. In ‘else’ part we are displaying the message to inform the student that he failed in the exam since he got marks less than 40.

Note that whenever the condition of ‘if’ statement returns false, the program executes the code block of ‘else’ part.

When you compile and run the app, you will see the result as shown in the output.

In the above code since marks obtained are below 40, the student failed, and that’s why the program executes the code block of ‘else’ part.

If you change the marks in the first line of code and set it to any value greater than or equal to 40 and again compile and run the app, then ’if’ condition will return true and the program executes the code block of ’if’ part.

C# Fundamentals