If Statement in C++
If statement Definition :
The If statement in C++ is used to carry out operations depending on a particular situation. If the provided condition is true, then the operation described in a certain statement or block of statements will be executed otherwise not.
Syntax:
if(condition){ // statements to be executed if condition is true; }
Working of if statement in C++:
- Step 1 : In the first step, condition/expression inside parenthesis is checked whether it is true or false.
- Step 2 : If statement is True, statements inside if block will be executed for performing the operations.
- Step 3 : If the condition is False , statements after the end of if block will be executed
Note:
Here, if curly braces'{}' are not provided after if(condition) then in C++ ,by default only the first statement which is immediately below the if statement which is present inside if block will be considered.
Example 1:
Run
#include<iostream> using namespace std; int main() { int j = 7; if (j > 1) { // checking the condition and take decision cout<<"PrepInsta is one of the best for placement preparation"< < endl; } cout<<"Prepinsta"< < endl; return 0; }
Output:
PrepInsta is one of the best for placement preparation Prepinsta
In the above example , the value of j initialize as 7 and when the condition of if (j>1) is checked , this is taken as true and both the statements inside if block is executed and “PrepInsta is one of the best for placement preparation” and “PrepInsta” will be printed on the output screen.
Example 2:
Run
#include<iostream> using namespace std; int main() { int j = 7; if (j < 1) { // checking the condition and take decision cout<<"PrepInsta is one of the best for placement preparation"< < endl; } cout<<"Prepinsta"< < endl; return 0; }
Output:
PrepInsta
In the above example , the value of j initialize as 7 and when the condition of if (j<1) is checked , this is taken as false and first statement at end of if block is executed and “PrepInsta” will be printed on the output screen.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment