6_switch.pdf
Document Details
Uploaded by DoctorVisionaryAngel
Seneca Polytechnic
Related
- PCSII Depression/Anxiety/Strong Emotions 2024 Document
- A Concise History of the World: A New World of Connections (1500-1800)
- Human Bio Test PDF
- University of Santo Tomas Pre-Laboratory Discussion of LA No. 1 PDF
- Vertebrate Pest Management PDF
- Lg 5 International Environmental Laws, Treaties, Protocols, and Conventions
Full Transcript
PRG 155 – Programming Fundamentals Using C 6. switch Statement Switch statement is used to easily select one option from a number of options when making a decision. How it works? A switch value is compared to a list of values called cases. The switch value might be a variable, an expre...
PRG 155 – Programming Fundamentals Using C 6. switch Statement Switch statement is used to easily select one option from a number of options when making a decision. How it works? A switch value is compared to a list of values called cases. The switch value might be a variable, an expression, or a direct value. Whenever is found that the switched value is equal to a case value, the block of code associated with that case is executed. The execution continues with the statements of the next case (or cases) until the break statement is encountered. The break statement is used to prevent the execution of the case or cases that follow. The break statement is optional. If no case value is found to be equal to the switched value, a special case called default is executed. The default case is optional. Syntax PRG 155 – Programming Fundamentals Using C switch Statement Flowchart Rules to follow when using switch statement: switch and case are keywords; must be written in lower case letters. Relational operators are not allowed in switch statement. The data type of case value and the switch value must be the same: integer or character. A switch statement can have any number of cases. Each case is followed by the case value and colon (‘:’). Two or more cases can share one break statement. The case values can be in any order. The default can be placed anywhere in the switch. No break is needed in the default case. PRG 155 – Programming Fundamentals Using C Example: int i= 2; switch (i) { case 1: printf("too low"); break; case 2: case 3: printf("good number"); break; default: printf("too high"); } References Tan, H.H., and T.B. D’Orazio. C Programming for Engineering & Computer Science. USA: WCB McGRaw-Hill. 1999. Print. Tutorialspoint.com. "Switch statement in C." Www.tutorialspoint.com. N.p., n.d. Web. 14 Feb. 2017.. Rajinikanth. "C Programming Language." C switch statement | c control statements | conditional control statements in c | C by Rajinikanth | C Programming Language. N.p., n.d. Web. 14 Feb. 2017.. "C switch...case Statement." C switch...case Statement. N.p., n.d. Web. 14 Feb. 2017..