You are on page 1of 15

CHAPTER 7

Common If Statement Errors, Else-If, Switch

printf(What grade are you in?); scanf(%d, &grade); if(6 <= grade <= 8) printf(You can go to the camp!\n); else printf(Sorry, you cannot go to the camp.\n);

COMPOUND EXPRESSIONS
printf(What grade are you in?); scanf(%d, &grade) if(6 <= grade && grade <= 8) printf(You can go to the camp!\n); else printf(Sorry, you cannot go to the camp.\n);

if(age >= 18) adult = 1; vote = 1; if(age >= 18) adult = 1; vote = 1;

FORGOTTEN BRACES
if(age >= 18) { adult = 1; vote = 1; }

if(age >= 18); { adult = 1; vote = 1; }

EMPTY STATEMENT
if(age >= 18) { adult = 1; vote = 1; }

if(<conditional expression>); creates an empty statement where, if the conditional expression is true, nothing is executed.

if(age < 18) ; else { adult = 1; vote = 1; }

if (age >= 13) if (age >= 18) printf(You can rent adult games!\n); else printf(You can only rent games that are for everyone. \n); printf(Go rent some games!\n);

MATCHING ELSE
if (age >= 13) { printf(You can rent teen games!\n); if (age >= 18) printf(You can rent adult games!\n); } else printf(You can only rent games that are for everyone.\n); printf(Go rent some games!\n);

Suppose an additional category was added for people 10 and up. How would we have to adjust the nested If Statements?

IMPLICIT NESTING
if (<conditional expression1>) statement1; else if (<conditional expression2>) statement2; else statementn;

PRACTICE

Write a short program that uses implicitly nested if statements to output a response to a users score in a game.

Score 300 250 200 < 200

Output You did excellent! You did great! You did well! Practice makes Perfect!

SWITCH STATEMENT
switch (<controlling expression>) { case <value1>: <stmts1> break; case <value2>: <stmts2> break; ... default: <stmtsn> } stmtA;

PRACTICE

Write a short program that allows the user to choose a box of Girl Scout Cookies. The switch statement should print out the price of the box based on the selected flavor. For the default case, print out that the user has not selected any cookies. Cost $3.00 $2.50 $2.00 Flavor Thin Mints Samoas Shortbread

You might also like