C++ Decision-making structures (if, switch)

 In C++, the two most commonly used decision-making structures are the if statement and the switch statement.

The if statement is used to execute a block of code if a condition is true. The general syntax of an if statement is as follows:

sql
if (condition)
 {
// code to execute if condition is true 
}

For example:

c
int x = 5
if (x > 0
{
cout << "x is positive"
}

In this example, if the value of x is greater than 0, the message "x is positive" will be displayed.

The switch statement is used to select one of several code blocks to execute, based on the value of an expression. The general syntax of a switch statement is as follows:

java
switch (expression) 
{
case value1:
// code to execute if expression == value1 
break;
case value2:
// code to execute if expression == value2 
break
 .
 . 
 . 
default: // code to execute if none of the cases match 
}

For example:

c
int day = 2
switch (day) 
case 1
cout << "Monday"
break
case 2:
cout << "Tuesday"
break;
default
cout << "Invalid day"
}

In this example, the value of the variable day is checked, and depending on its value, one of the corresponding messages is displayed. If the value of day is not 1 or 2, the message "Invalid day" is displayed. Note that each case statement must end with a break statement to prevent the execution of the following case statements.

Comments

Popular posts from this blog

Introduction to Computer

History of Computer

Computer Generation