Conditional structure: if and else
- The if statement executes based test expression inside the braces.
- If statement expression is to true, If body statements are executed and Else body statements are skipped.
- If statement expression is to false If body statements are skipped and Else body statements are executed.
- Simply, Block will execute based on If the condition is true or not.
- IF conditional statement is a feature of this programming language which performs different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch prediction, this is always achieved by selectively altering the control flow based on some condition.
if and else Syntax
if (expression) // Body will execute if expression is true or non-zero
{
//If Body statements
}else
{
//Else Body statements
}
if and else Syntax Example
for example, In c
if (i == 3) {
doSomething();
}
else {
doSomethingElse();
}
Syntax Explanation
Consider above example syntax,if (i == 3)
- which means the variable i contains a number that is equal to 3, the statements following the doSomething() block will be executed.
- Otherwise variable contains a number that is not equal to 3, else block doSomethingElse() will be executed.
Example Program For If..else
/* Example Program For If..else In C++ Programming Language */
// Header Files
#include<iostream>
using namespace std;
//Main Function
int main()
{
// Variable Declaration
int a;
//Get Input Value
cout<<"Enter the Number :";
cin>>a;
//If Condition Check
if(a > 10)
{
// Block For Condition Success
cout<<a <<" Is Greater than 10";
}
else
{
// Block For Condition Fail
cout<<a<<" Is Less than/Equal to 10";
}
//Main Function return Statement
return 0;
}
Sample Output:
Enter the Number :8
8 Is Less than/Equal to 10
Enter the Number :10
10 Is Less than/Equal to
Comments
Post a Comment