flowcontrol

description of image


Decision Making (if, if else)


In programming, there may arise a situation where we may need to run a block of code among multiple alternatives.


For example,

assigning grades A, B, or C based on the marks obtained by the student.

In such situations, we use the if statement to create programs that can make decisions.



If Statement :


● The syntax of the if statement Is:

If(testCondition) {

// code to execute

}

The if statement evaluates the testCondition like: age >= 18

If the testCondition evaluates to

True – the body of the if statement is executed

False – the body of the if statement is skipped

Let’s see a working example next.



Example 1: if Statement


● This program checks whether a number is negative or not.



if else Statement :


● The if statement can have an optional else clause.

Its syntax is:

If (testCondition) {

// body of if

}

else {

// body of else

}

How if…else works?

The program evaluates the testCondition. If the testCondition evaluates to

True – the body of if is executed

False – the body of else Is executed



Quiz


Question Text