If else Statement
If statement
Sometimes you have to make decisions based on the conditions that are created during the program. So, if statement is used in that kind of situations. It checks whether a condition is satisfied or not. If yes then it runs otherwise skips.Syntax: if(expression)
statement;
statement can be a single statement, a compound statement or can be blank. If the expression is true then the statement is executed otherwise ignored.
Else statement
It is executed when the if statement becomes false. It is optional to include the else statement but I will recommend you that you use it because sometimes you want to see whether your statement worked or failed during execution.Let's understand this with an example.
Program:
#include<iostream.h>#include<conio.h>
void main()
{
clrscr();
int a,b;
a=10;
b=20;
if(a>b)
cout<<"a is greater than b";
else
cout<<"b is greater";
}
Now when the program will execute, it will go to the assigned values, then will start with if statement. So the first statement becomes false because a is not greater than b. Then it will display the else statement. So the output will be: b is greater.
No comments:
Post a Comment