Week 04
Week 04
COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]
2
The Controlling Statement
Switch statement
• A switch statement's controlling statement must return one
of these basic types:
• -A bool value
• An int type
• A char type
• switch will not work with strings in the controlling statement.
4
Can I Use the break Statement in a Loop?
5
C++ Switch Statements
• Use the switch statement to select one of many code blocks to be executed.
• Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
6
How it works:
7
The example below uses the weekday number
to calculate the weekday name:
8
The break Keyword
• When C++ reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is
no need for more testing.
• A break can save a lot of execution time because it "ignores" the execution
of all the rest of the code in the switch block.
9
The default Keyword
10
The default Keyword
11
Blocks
12
Local vs. Global Variables
13
Local vs. Global Variables - Example
14
Local vs. Global Variables - Example
Output??
15
Local vs. Global Variables - Example
Output??
CS 98.CS 98.CS 98
16
goto Statement
• You can write any C++ program without the use of goto statement and
is generally considered a good idea not to use them.
19
Reason to Avoid goto Statement
• The goto statement gives the power to jump to any part of a program but,
makes the logic of the program complex and tangled.
• The goto statement can be replaced in most of C++ program with the use of
break and continue statements.
20
Enumeration
• An enumeration is a user-defined data type that consists of integral
constants. To define an enumeration, keyword enum is used.
• enum season { spring, summer, autumn, winter };
• Here, the name of the enumeration is season.
• And, spring, summer and winter are values of type season.
• By default, spring is 0, summer is 1 and so on. You can change the default
value of an enum element during declaration (if necessary).
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
21
Enumerated Type Declaration
• When you create an enumerated type, only blueprint for the variable is created. Here's
how you can create variables of enum type.
// inside function
enum boolean check;
• Here is another way to declare same check variable using different syntax.
enum boolean
{
false, true
} check;
22
Example 1: Enumeration Type
#include <iostream>
using namespace std;
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Output
Day 4
23
Example2:
Changing Default Value of Enums
#include <iostream>
using namespace std;
Output
Summer = 4
24
Example2:
Changing Default Value of Enums
#include <iostream>
using namespace std;
Output
Summer = 4
25