Lecture 7
Lecture 7
Fundamentals
int main() {
int a = 10, b = 20;
int main() {
int num = 5;
// Using the conditional operator
string result = (num % 2 == 0) ? "Even" : "Odd";
cout << num << " is " << result << endl;
return 0; }
Output:
5 is Odd
2. Switch statement in C++
The switch statement in C++ is a control
structure that allows you to choose one block
of code to execute out of many possible
options, based on the value of an expression.
It is an alternative to a series of if-else
statements when you are checking the same
variable for multiple values.
Syntax:
switch (expression) {
case constant1:
// Code to execute if expression == constant1
break;
case constant2:
// Code to execute if expression == constant2
break;
// Additional cases as needed
default:
// Code to execute if no case matches
}
expression: An integral or enumerated
type( user-defined data type) (e.g., int, char,
enum) whose value is compared against
constants.
case constant:: Defines a specific value to
compare the expression against.
break: Exits the switch statement. If omitted,
execution will "fall through" to the next case.
default: Optional; executed if none of the case
values match the expression.
How It Works
The expression is evaluated.
The program compares the value of
expression with each case constant.
When a match is found, the corresponding
code block is executed.
If no match is found, the default block (if
present) is executed.
The break statement stops execution of the
switch and prevents fall-through.
Example 1: Days of the Week
int main() {
int day = 3;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
cout << "Invalid day" << endl; }
return 0; }
Output:
Wednesday
Limitations of switch
goto label;
// Some code
label:
// Code to execute
int main() {
cout << "Start of the program." << endl;
goto skip; // Jump to the label 'skip'
cout << "This line will be skipped." << endl;
skip:
cout << "This line is executed after the jump." <<
endl;
return 0; }
Output:
Start of the program.
This line is executed after the jump.