C++ If Statement
The if statement in C++ is used to execute a block of code based on a condition. It allows decision-making in programs and is one of the most basic control flow structures.
1. Basic If Statement
The simplest form of the if statement executes a block of code when the condition evaluates to true.
C++
Example: Basic if statement
#include <iostream>
using namespace std;
int main() {
int num = 10;
if (num > 0) {
cout << "Number is positive" << endl;
}
return 0;
}
2. Common Mistakes
Avoid missing braces for multiple statements and ensure conditions are properly written with relational operators.
C++
Incorrect usage example
#include <iostream>
using namespace std;
int main() {
int num = 5;
if (num > 0)
cout << "Positive" << endl;
cout << "This will always execute" << endl; // Misleading without braces
return 0;
}
Conclusion
C++ if statements are the foundation of conditional logic. Learning proper usage of if statements helps control the flow of your programs effectively.
Codecrown