Lecture-9_switch_function

Lecture-9_switch_function - It is often necessary in...

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

View Full Document Right Arrow Icon
Computer Science I - Martin Hardwick Lecture 1 -- 1 Odds And Ends – Switch Statement It is often necessary in programs to set up a set of cases, where at most one of the cases is executed. we have done this with nested IF-ELSE statements There is a special statement in C++ that makes is easier to set up cases in some situations. it is called the switch statement switch (score/10) {     case 0: case 1: case 2:     case 3: case 4: case 5:     F = F + 1;  break;     case 6: D = D + 1;  break;     case 7: C = C + 1;  break;     case 8: B = B + 1;  break;     case 9: case 10: A = A + 1;  } if (score < 60) {     F = F + 1; } else if (score < 70) {     D = D + 1; } else if (score < 80) {     C = C + 1; } . . . Example Counting letter grades for exam scores.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Computer Science I - Martin Hardwick Lecture 1 -- 2 Switch Statement Syntax: switch ( <expr> ) { case <a>: case <b>: . . . statement1; statement 2; . . . break; case <x>: case<y>: . . . statement10; statement20; . . . break; . . . default: statement100; statement200; . . . } Meaning: <expr>==<a> || <expr> == <b> || . . . <expr>==<x> || <expr> == <y> || . . . . . . yes yes no no statement 1 statement 2 . . . statement 10 statement 20 . . . statement 100 statement 200 . . .
Background image of page 2
Computer Science I - Martin Hardwick Lecture 1 -- 3 Break Break is used to break out of a For, While and Switch In a Switch if there is no break then the code will continue into the next case This can be a good thing for some programs However it is a frequent cause of errors for beginners Make sure that your Cases end in a break or a return.
Background image of page 3

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

View Full DocumentRight Arrow Icon
Computer Science I - Martin Hardwick Lecture 1 -- 4 Putting it all together This program uses everything A while loop to get data until 
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/04/2011 for the course CS 2400 taught by Professor Richie during the Spring '11 term at Rensselaer Polytechnic Institute.

Page1 / 11

Lecture-9_switch_function - It is often necessary in...

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

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