Programming in c++ Additional Control Structures Dale/eems/Headington
1 Additional Control Structures
Programming in C++ Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping s For Statement for Looping % Using break and continue Statements To be able to choose the most appropriate looping statement for a given problem
2 Chapter 9 Topics ❖Switch Statement for Multi-way Branching ❖Do-While Statement for Looping ❖For Statement for Looping ❖Using break and continue Statements ❖To be able to choose the most appropriate looping statement for a given problem
Programming in C++ Switch Statement Is a selection control structure for multi-way branching SYNTAX switch( IntegralExpression case Constant Statement 1 ∥ optional case Constant2 Statement 2. ∥ optional default ∥ optional Statement n ∥ optional
3 Switch Statement Is a selection control structure for multi-way branching. SYNTAX switch ( IntegralExpression ) { case Constant1 : Statement 1; // optional case Constant2 : Statement 2; // optional . . . default : // optional Statement n; // optional }
Programming in C++ float weightin Pounds =165.8; char weightUnit M/ user enters letter for desired weightUnit switch( weightUnit case“P casep. cout≤ weightln Pounds≤≤“ pounds“≤<endl break case case‘o3 cout≤<16.0* weightIn Pounds≤“ ounces“≤<endl; break case“K case“k cout < weightIn Pounds/22≤≤“klos“<end; break case‘G case ' g cout≤<454.0* weightin Pounds<“ grams“≤<end break default cout≤<“ That unit is not handled!“≤endl; break 4
4 float weightInPounds = 165.8 ; char weightUnit ; . . . // user enters letter for desired weightUnit switch ( weightUnit ) { case ‘P’ : case ‘p’ : cout << weightInPounds << “ pounds “ << endl ; break ; case ‘O’ : case ‘o’ : cout << 16.0 * weightInPounds << “ ounces “ << endl ; break ; case ‘K’ : case ‘k’ : cout << weightInPounds / 2.2 << “ kilos “ << endl ; break ; case ‘G’ : case ‘g’ : cout << 454.0 * weightInPounds << “ grams “ << endl ; break ; default : cout << “That unit is not handled! “ << endl ; break ; }
Programming in C++ Switch Statement o the value of IntegralExpression (of char, short, int, long or enum type) determines which branch is executed o case labels are constant( possibly named integral expressions, Several case labels can precede a same statement
5 Switch Statement ❖the value of IntegralExpression (of char, short, int, long or enum type ) determines which branch is executed ❖case labels are constant ( possibly named ) integral expressions. Several case labels can precede a same statement