Decision Making and Branching - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Decision Making and Branching - Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, March 15, 2019

Decision Making and Branching


Decision Making and Branching


üWhen a program breaks the sequential flow and jumps to another part of the code, it is known as branching. When branching is done on a condition it is known as conditional branching.
üThree decision making statements:
  1. if statement
  2. switch statement
  3. conditional operator statement
The if Statement


The if-else Statement


üAn else clause can be added to an if statement to make an if-else
 statement.

if ( condition )


   statement1;

else

   statement2;

Statement x;

üIf the condition is true, statement1 is executed;  if the 
condition is false, statement2 is executed.


üOne or the other will be executed, but not both.

Nested if….Else Statements

üThe if..else statement can be contained in another if or else statement.
  if (test condition1)

  { 

  if (test condition2)

  statement-1;

  else

  statement-2;

  }

  else

  statement-3;
 
  statement-x;

Nested if….Else Statements

üAn else clause is matched to the last unmatched if (no 
matter what the indentation implies!)
üExample:

  if(female)

  if(bal>5000)

  bon = 0.05 * bal;

  else

  bon = 0.02 * bal;

  bal = bal + bon;
üBraces can be used to specify the if statement to which an
 else clause belongs.
Multiway Selection: Else if
üSometime you want to select one option from several 

alternatives

if (conditon1)

    statement1;

else if (condition2)

    statement2;

else if (condition3)

    statement3;

else

    statement4;


Else if example

double numberGrade = 83.6;

char letterGrade;

if (numberGrade >= 89.5) {

    letterGrade = ‘A’;

} else if (numberGrade >= 79.5) {

    letterGrade = ‘B’;

} else if (numberGrade >= 69.5) {

    letterGrade = ‘C’;

} else if (numberGrade >= 59.5) {

    letterGrade = ‘D’;

} else {

    letterGrade = ‘F’;

}

System.out.println(“My Grade is ” + numberGrade + 

“, ” + letterGrade);


OUTPUT


My Grade is 83.6, B

No comments:

Post a Comment

Post Top Ad