If Block
Published by
sanya sanya
The "if" block is a conditional statement in programming that allows you to execute a block of code based on a specified condition. It provides a way to control the flow of execution in your program by selectively executing code based on whether a condition evaluates to true or false.
When to use:
You can use the "if" block when you want to perform an action or execute a specific block of code only if a certain condition is met. It allows you to make decisions and execute different code paths based on the outcome of the condition.
Syntax:
- Single "if":
if (condition) {
// code to be executed if the condition is true
}
- "if-else":
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
- "if-else if-else":
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
Code examples:
- Single "if":
#include
using namespace std;
int main() {
int num = 5;
if (num > 0) {
cout << "Number is positive." << endl;
}
return 0;
}
- "if-else":
#include
using namespace std;
int main() {
int num = -2;
if (num > 0) {
cout << "Number is positive." << endl;
} else {
cout << "Number is non-positive." << endl;
}
return 0;
}
- "if-else if-else":
#include
using namespace std;
int main() {
int num = 0;
if (num > 0) {
cout << "Number is positive." << endl;
} else if (num < 0) {
cout << "Number is negative." << endl;
} else {
cout << "Number is zero." << endl;
}
return 0;
}
Compulsory and optional blocks:
- For the single "if" statement, the block inside the "if" statement is compulsory. It contains the code to be executed if the condition is true.
- For the "if-else" statement, both the "if" and "else" blocks are compulsory. The "if" block contains the code to be executed if the condition is true, and the "else" block contains the code to be executed if the condition is false.
- For the "if-else if-else" statement, the "if" block is compulsory, and at least one "else if" or "else" block is optional. The "if" block contains the code to be executed if the first condition is true. "else if" blocks allow you to check additional conditions, and the "else" block contains the code to be executed if all conditions are false. You can have multiple "else if" blocks if needed.
The choice of using "if" alone, "if-else," or "if-else if-else" depends on the specific logic and decision-making requirements in your program.
Library
WEB DEVELOPMENT
FAANG QUESTIONS