alg3 - Basics of Algorithms Chapter 3 Nested Conditional...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Nested Conditional Statements The if-else statement can be nested to allow the programmer the ability to program a complex decision structure. The general form of a nested if-else statement is shown below: if (<boolean expression1>) <statements 1> else if (<boolean expression2>) <statements 2> else if (<boolean expression3>) <statements 3> . . . else <statements n> statement A statement B . . . This statement is executed as: 1. Check if <boolean expression1> is true 2. If so, then execute block of statements <statements 1> 3. If not, check if <boolean expression2> is true 4. If so, then execute block of statements <statements 2> 5. If not, check if <boolean expression3> is true 6. Continue in this fashion until one of the boolean expressions is true 7. Skip all remaining blocks of statements and continue execution with statement A, …. Note: The else clause is always optional. There may be cases in which you do not want to execute any statements based upon a particular decision. Algorithms - 26 Basics of Algorithms – Chapter 3
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Examples Note: Having the conditions in the wrong order can lead to errors as the following example illustrates: Nested If Statements Algorithms - 27 /********************* Assigning Letter Grades **********************************/ int num_avg; char letter_grade; scanf(“%d”, &num_avg); /* input numerical average score */ if (num_avg >= 90) letter_grade = ‘A’; else if (num_avg >= 80) letter_grade = ‘B’; else if (num_avg >= 70) letter_grade = ‘C’; else if (num_avg >= 60) letter_grade = ‘D’; else letter_grade = ‘F’; printf(“Your grade is: %c\n”); /************ Assigning Letter Grades - BAD EXAMPLE *********************/ int num_avg; char letter_grade; scanf(“%d”, &num_avg); /* input numerical average score */ if (num_avg < 60) letter_grade = ‘F’;
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

alg3 - Basics of Algorithms Chapter 3 Nested Conditional...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online