Decision Making Statements – If Statement

October18, 2017
by admin

Syntax:


  if(<conditional expression>)
  {
    // statement or statements be executed
    // when conditional expression return 
    // true
  }

If statements execute the statements within the code block(i. e. within the curly brace) when conditional expression (or you may call it as a boolean expression) returns true. If it returns false then statements are skipped.

Ex:

Problem:

Write a program to show the output displaying if the student passed the examination. Passing marks are 40. If a student failed then no message need to be displayed.

Solution:


  int marks = 75;

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

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

  System.Console.WriteLine("Sorry... You are unable to get the passing marks");

Output:

Marks obtained in exam: 40
You are passed the examination

In above code, we are checking whether the student gets the minimum marks to pass (40 or greater than 40).

If the marks obtained by the student are greater than or equal to 40 then conditional expression return true and we write to console output to inform that student is passed.

If the marks obtained are less than 40 then the code within the code block is skipped and the next statement outside the code block is executed which writes to the console output informing the student about the result.

Since we have hard coded the marks for this example to 75, when we compile and run this example code, we get the output as expected by satisfying the conditional expression.

C# Fundamentals