If Statement With Example

What is if-Statement

The if-statement is a decision-making statement. It is the simplest form of conditional structure. It is used to execute or skip a statement or set of statements by checking a condition.

If Statement With Example

The condition is given as a relational expression. If the condition is true, the statement or set of statements after if statement is executed. If the condition is false, the statement or set of statements after if statement is not executed.

Syntax

The syntax of if statement is as follows:

if (condition) statement

The above syntax is used for single statement. A set of statements can also be made conditional. In this case, these statements are written in curly brackets. The set of statements is also called compound statements.

The syntax for compound statements in if statement is as follows:

if (condition)

{

statement 1;

statement 2;

statement N;

}

Limitation of if Statement

The if statement is the simplest selection structure but it is very limited in its use. The statement or set of statements is executed if the condition is true. But if the condition is false then nothing happens. A user may want to:

  • Execute one statement or set of statements if the condition is true.
  • Execute other statement or set of statements if the condition is false.

In this situation, simple if statement cannot be used effectively.

Example

Suppose a program should display 'Pass' if the student gets 40 or more marks. It should display 'Fail' if the student gets less then 40 marks. Simple if statement cannot be used to handle this situation.

Post a Comment

0 Comments