If and else statement:
In c++ the
compiler run our program instruction by instruction or line by line.Sometime we have some specific statement or instruction
that we want to run when certain condition full fill. For this c++ provide the
conditional statement. If statement use
for this purpose .
Syntax
If(condition)
Statement ;
If is a keyword that take a
condition if the condition is true then the statement will be run otherwise the
statement will not be run.
Example:
If(x==100)
Cout<<”congrats your condition is true”;
You can use more than one statement that is effect by if condition for this we use {}. Every statement that will be written within {} will be run when if condition is true
Syntax
If(condition)
{
Statement 1;
Statement 2;
.
.
.
Statement n;
}
Example:
If(x==100)
{
Cont<<”the value of x is 100”;
Cout<<”congratulaion your output is diaplaying”;
Cout<<”this example is written by
programminglogic.net”;
}
If condition will be false than
nothing will be happened no output will be display. so if we want that when conditon will false some instruction should
be run then we use if else
Syntax of if ,else statement
If(condition)
Statement;
else
Statement;
Syntax for more than one statement
If(condition)
{
Statement 1;
Statement 2;
.
.
Statement n;
}
else
{
Statement 1;
Statement 2;
.
.
Statement n;
}
Example:
If(x==100)
Cout<<”the value of x is 100”;
else
Cont<<”the value of x is less than or greater than
100”;
Flow chart of if ,else statement:
if else |
Nested if ,else:
We use if ,else statement for
conditional statement when we have multiple condition which is related to each
other then we use nested if ,else . we can simply say that a nested if ,else
statement is an if ,else statement with
another if else statement inside
it . we use it when we have more than
one choice .
Syntax of nested if,else statement:
If(condition)
//Some code
elseif(condition)
//some code
Elseif(condition)
//some code
.
.
.
.
.else
//Some code
The nested if
else statement means that if
the top condition is not true, then try checking other condition. If anyone
condition is true , then ignore the rest of the available conditions. If no one
condition is true then execute the else part of the statement .
flow chart:
nested if else |
0 comments:
Post a Comment