Control Structures in C++
Control structures are fundamental elements in C++ that dictate the flow of a
program. They enable decision-making, looping, and branching to execute specific
parts of the code based on conditions or repetitions.
1. Types of Control Structures
1.1 Conditional Control Structures
These structures allow the program to make decisions and execute code
selectively based on conditions.
1.1.1 if Statement
Executes a block of code if the given condition evaluates to true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
int a = 10;
if (a > 5) {
cout << "a is greater than 5.";
}
1.1.2 if-else Statement
Provides an alternative block of code to execute if the condition is false.
, Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int a = 3;
if (a > 5) {
cout << "a is greater than 5.";
} else {
cout << "a is less than or equal to 5.";
}
1.1.3 else-if Ladder
Checks multiple conditions sequentially.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}
Example:
int marks = 85;
if (marks >= 90) {
cout << "Grade: A";
} else if (marks >= 75) {
cout << "Grade: B";
Control structures are fundamental elements in C++ that dictate the flow of a
program. They enable decision-making, looping, and branching to execute specific
parts of the code based on conditions or repetitions.
1. Types of Control Structures
1.1 Conditional Control Structures
These structures allow the program to make decisions and execute code
selectively based on conditions.
1.1.1 if Statement
Executes a block of code if the given condition evaluates to true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
int a = 10;
if (a > 5) {
cout << "a is greater than 5.";
}
1.1.2 if-else Statement
Provides an alternative block of code to execute if the condition is false.
, Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int a = 3;
if (a > 5) {
cout << "a is greater than 5.";
} else {
cout << "a is less than or equal to 5.";
}
1.1.3 else-if Ladder
Checks multiple conditions sequentially.
Syntax:
if (condition1) {
// Code for condition1
} else if (condition2) {
// Code for condition2
} else {
// Code if none of the conditions are true
}
Example:
int marks = 85;
if (marks >= 90) {
cout << "Grade: A";
} else if (marks >= 75) {
cout << "Grade: B";