if-else statement in C plus plus




The if-else statement in C++


The if then else statement is used when the question is not whether to execute a statement or statements, but which statement or statements to execute. The simplest if-else construct consists of two options, and its format is:

If (logical expression)
statement 1 or block 1;
else
statement 2 or block 2;
next_statement

If logical expression is TRUE, statement1 (or block1) is executed and then next_statement is executed. If logical expression is FALSE, statement2 (or block2) is executed and then next_statement is executed.
For e.g., the following program segment informs the user concerning the existence of real solutions in the quadratic equation.
Let a, b, c be the coefficients of the quadratic equation. Then if the roots are real, the discriminate d=b2-4ac will be greater than or equal to zero.i.e.,

D=b*b-4*a*c;
If(d>=0) then
Message: “roots are real”
else
Message: “roots are imaginary”
For e.g., The following program segment reports which number is the larger of 2 numbers given.
int a, b;
//user inputs two numbers a and b
if (a > b)
The larger number is: “a”;
else
The larger number is: “b”;


The number of options in an if-else-if construct is not limited to two, and frequently more are used in a program. The general form is:

if (logical expression 1)
                    statement 1 or block 1;
else if (logical expression 2)
                                    statement 2 or block 2;
else if (logical expression 3)
                                    statement 3 or block 3;
else if (logical expression 4)
                                    statement 4 or block 4;
else
next_statement;

As it consistent with the simpler if-else construct, if logical expression 1 is TRUE, statement1 is executed and program control passes to next_statement. If logical expression 1 is FALSE, statement2 is checked, and so on. If none of the expressions are TRUE, control passes to the next_statement without any of the statements in the else-if clauses having been executed.
Example:
// the following program segment finds the number of real roots in a quadratic equation.
Float a, b, c, discriminant;
Unsigned int nRoots;
// Input the coefficients of a quadratic function (a, b, c);
discriminant = (b *b) – (4*a*c);
if (discriminant > 0)
“There are two roots to the quadratic function.”;
elseif (discriminant == 0)
“There is one root to the quadratic function.”;
else
“There are no roots to the quadratic function.”;

Flow-chart of if-else statement



Comments

Popular posts from this blog

Rumors of women’s hair cutting in India

President of India

Java interview question answer