C++ Programming

decision making statement if, if-else, nested-if, switch case

Decision-Making Introduction:

Decision-Making Statement if, if-else, nested-if, switch case-You know that computers can perform arithmetic calculations correctly and rapidly. Besides rapid arithmetic calculations and other capabilities, the computer is also capable of quick decision making and repetition. In this tutorial you will learn how to make decisions in c/c++ i.e you will learn how to code the program so that computer tests a condition and selects one of two alternative actions depending on whether the condition is true or false c/c++

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Transfer of control process:

Normally statements in a program are executed sequentially one after the other in increasing order i.e in the same order in which they appear in the program however it is possible to override this normal sequential order because in certain application it becomes necessary to interrupt the normal sequence and transfer control to some other part of the program. this is call transfer of control. The transfer of control process can be defined as the process of altering the normal sequence in which statements are executed. In c/c++ the transfer of control is achieved by goto, if or if-else and switch statements. Let us discuss these statements in detail.


The unconditional Jump goto statement:

As discussed earlier that statements are executed one after another in their natural sequence (i.e in gravitational flow). But the order of execution may be changed with a direct (unconditional) jump. In c++ this can be accomplished by means of the goto statement. The goto statement branches unconditionally to a specified labeled-statement. It has the following general form

Goto label;

:

:

Label: statement;

The keyword goto is always followed by a label (a label to which control will be transferred); where label is a valid identifier-name and must be unique in a program i.e no two statements can have the same label in a program.

C/c++ knows a label because it ends with a colon. When computer executes the goto statement it branches to that statement labeled by associated label.

Let us examine the program shown below:

#include <iostream.h>
Void main()
{
Int C= 0;
Jump:C = C+1;
Cout<<C<<endl;
Goto jump;
}
Output:
1
2
3
:
:

In the above program, the value of C is initially set to zero (int C = 0) such assignment is called initialization. When the computer encounters the statement C= C+1 the value of c is incremented by 1 i.e it sets C to 1. The statement cout<<C instruct the computer to print the value of C on screen. When the statement goto jump is encountered the program returns to labeled-statement jump:C=C+1 to execute the program the second time. at this time the value of C would become 2. This procedure will remain to continue until the user terminates the execution of the program by pressing the Ctrl-Break key.

Avoid using the goto statement whenever possible because modern programming practice discourage its use. It is generally felt that goto statements make a program harder to read and debug. Therefore never ever use goto statement. The structured features of C language eliminate the need of goto by writing more structured programs using other branching statements (for, while and do/while)a well.



Decision-Making with if statement:

the fundamental decision-making statement in C/c++ is the if statement. it enables you to test for a condition to perform some action. Its simplest format is

for a single statement:

if(condition)

          statement;

for multiple statements:

if(condition)

{

Statement1;

Statement2;

:

:

}

The reserved word if is followed by a  condition which is followed by a statement to be carried out if the condition is true. A statement may be a single statement or a block of statements or nothing (in case of null statement). When more than one statements are going to executed after the if statement then the statements must be grouped by enclosing them within a pair of braces. Every statement in the if block must end with a semicolon.

Here is a portion of a C/C++ program with an if statement which illustrates the use of this important statement.

If(pay> 40000)

          Tax=0.10 * gross_pay;

Net_pay = gross_pay – Tax;

In the above example the condition (pay > 400000) is tested. In this case the value of pay is larger than the 40000 then the logical condition is true and the statement (Tax = 0.10 * gross_pay) following the condition is executed and the computer then goes on to execute whatever statement follows the semicolon which ends the if statement. However if pay is not larger than 40000 (i.e condition is false) then the statement following the condition will be ignored and control will be transferred to the next statement (i.e Net_pay= gross_pay – Tax) following the semicolon which ends if statement. So the statement following the condition will be obeyed or ignored according to the condition being true or false.


The if statement is flowcharted with the familiar diamond or decision symbol as shown in the figure

decision making

Example: how to write a program which start beep when the marks is poor:

#include <iostream.h>
#include <conio.h>
void main()
{
int marks;
cout<<”Enter the student marks : ”;
cin>>marks;
if(marks < 30)
{
cout<<’\x07’;
cout<<”Fail”<<endl;
cout<<”Poor Result”<<endl;
}
cout<<”\nmarks = ”<<marks;
getch();
}


Decision-making with if-else statement:

The  second most useful decision-making statement is if-else statement. The general form of if-else statement Is follow:

If(condition)

Statement;

Else

          Statement;

With if-else statement if condition is true, the statement or statements immediately following the condition is executed. If the condition is false the else clause is executed.

Any type and any number of statements may appear before and after the else clause. As usual statements must be enclosed within braces for more than one statement.

With if-else statement we test a condition and we perform one of two alternatives i.e it is used in program solutions to perform one action when a given condition is true and a different action when the condition is false. It is similar to the simplest form of the if statement but there is a difference . the simplest form of the if statement performs an indicated action only when the condition is true whereas the if-else statement allows the programmer to specify separate actions to be performed when the condition is true or when the condition is false. The following figure illustrates the flowchart for the if-else statement.

let us consider the if-else statement in the following:

if(marks > 33)

          cout<<”Pass”;

else

          cout<<”Fail”;

the above statement will display “Pass”, if the student’s marks are higher than 33 and will display “ Fail “ if marks are less than 33. As usual statement must be enclosed within braces for more than one statement. For example

if(marks > 55)

{

          cout<<”Pass”;

          cout<<”\nCongrates”;

}

Else

{

          cout<<”Fail\n”;

          cout<<”Try Again”;

}

Example: how to write a program in c++ which display even and odd number using decision-making statement if-else:

#include <iostream.h>
#include <conio.h>
void main()
{
int no,reminder;
cout<<”Enter any Number : “;
cin>>no;
reminder = no % 2;
if(reminder == 0)
    cout<<”Number is Even”;
else
    cout<<”Number is odd”;
getch();
}

Example: write a program in c++ which display the basic pay of  the employee and calculate the net pay using decision-making statement if-else:

#include <iostream.h>
#include <conio.h>
void main()
{
int b_pay, c_allowance, m_allowance;
float h_rent,net_pay;
cout<<”Enter Basic Pay : “;
cin>>b_pay;
clrscr();
h_rent = b_pay * (45.0/100);
if(b_pay < 5000)
{
c_allowance = 300;
m_allowance = 150;
}
else
{
c_allowance = 750;
m_allowance = 500;
}
Net_pay = b_pay + h_rent + c_allowance + m_allowance;
Cout<<”Net pay = “<<net_pay;
}

Example: write a program in c++ which calculate the two roots of quadratic equation using  decision-making statement if-else:

The roots are calculated as:

  1. If discriminant (b2 – 4ac) = 0 then the roots are real

Root1= -b/(2.0 * a)

Root2= -b/(2.0 * a)

  1. If discriminant (b2 – 4ac)) < 0 then the root are imaginary

Root1= (-b + i(dicriminant)1/2) / (2.0 * a)

Root1= (-b – i(dicriminant)1/2) / (2.0 * a)

  1. If discriminant (b2 – 4ac) > 0 then the roots are real and unequal.

x=(-b±√(b^2-4ac))/2a

#include <isotream.h>
#include <conio.h>
#include <math.h>
Void main()
{
Int a,b,c;
Float R1, R2, Disc, Real, Imag;
Clrscr();
Cout<<”enter the value of  A :”; cin>>a;
Cout<<”enter the value of  B :”; cin>>b;

Cout<<”enter the value of  C :”; cin>>c;
Disc = b*b – 4.0 * a * c;
If(Disc == 0)
{
    R1 = R2 = -b/(2.0 * a);
    Cout<<”Roots are Real and Equal :”<<endl;
    Cout<<”Root1 = “<<R1<<endl;
    Cout<<”Root2 = “<<R2<<endl;
}
If(Disc < 0)
{
Real = -b/(2.0 * a);
Imag =  sqrt(-Disc)/(2.0 * a);
Cout<<”Root are Imaginary”<<endl;
Cout<<”Root1 = ”<< Real<<”+ i(”<<Imag<<”)”<<endl;
Cout<<”Root2 = ”<< Real<<”+-i(”<<Imag<<”)”<<endl;

}
If(Disc > 0)
{
R1 = (-b + sqrt(Disc))/(2.0 * a);
R2 = (-b - sqrt(Disc))/(2.0 * a);
Cout<<”Roots are Real and different”<<endl;
Cout<<”Root1 =”<<R1<<endl;
Cout<<”Root2 =”<<R2;

}

}

In the above program all the three if-conditions will be checked but if we use else-if from it will be executed only in that case if the conditions in all of the preceding if statements are false. Obviously it will lead to efficient programming.



Example: write a program in c++ which display subtraction division multiplication addition using decision-making statement if,  else if  and else :

#include <isotream.h>
#include <conio.h>
#include <stdlib.h>
Void main()
{
Char op;
Float x,y,z = 0.0;
Clrscr();
Cout<<”Enter first Number :”
Cin>>x;
Cout<<”Enter second Number :”
Cin>>y;
Cout<<”Enter any operator(-, *, +, /) :”;
Op=getche();
If(op==’+’)
    Z= x  + y;
Else if(op== ‘-’)
    Z=x – y;
Else if(op==’*’)
    Z=x * y;
Else if(op== ‘/’)
    {
    If(y != 0)
`       z=z/y;
`
`else
{
    `cout<<”\n\nDivision by Error”;
    Exit(0);
}
}
Cout<<”\n\n”<<x<<” “<<op<<” “<<y<<” “<<z;
Getch();
}
Output:
Enter first Number 4
Enter second Number 2
Enter any operator(-, *, +, /) +

4 +  2 = 6  

In the above program, exit() function is used which (declared in the stdlib.h header file) enables you to exit the program.

Decision-Making Nested-if statement:

The if structure can be nested within on another i.e when an if statement is contained within another we say these are nested or nest of conditional statements or a nested if.

A relatively simple example of a nested if statement is shown in the following

If(condition)

          If(condition)

                   Statements

          Else

                   Statement

Else

          Statement

The above example shows a simple type of nested decision making. Another example is give with different pattern of nested condition.

If(condition)

If(condition)

If(condition)

Statement

Else

Statement

Else

Statement

Else

Statement

In the above example we need to know which else phrase goes with which if. The rule is very simple each else clause belongs to the nearest if for which there is no else clause i.e each else is paired with the previous if that does not already have an else as shown below:

decision making

Apply this rule to the example just given and after proper indentation, we get the following pattern

decision making

Indentation plays an important role in nested if statement because it shows which else belongs to which if statement. It is a visual aid for the programmer. It is no requirement for the compiler but rather a good programming practice to make programs more readable.

Example: write a program in c++ which display the largest number using decision-making statement  nested if  :

#include <isotream.h>
#include <conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<”Enter the 3 value :”;
cin>>a>>b>>c;
if(a>b)
{
if(a>c)
    cout<<”the largest number is :”<<a;
else
    cout<<”the largest number is :”<<c;
}
else
{
    if(b>c)
cout<<”the largest number is :”<<b;
else
cout<<”the largest number is :”<<c;
}
getch();
}
}

Nested condition can be very useful in writing program statements but sometimes nested if statements can become extremely long which causes difficulty in reading understanding debugging and modifying the program logic poor indentation may cause a lot of problem for the programmer. So therefore it is always suggested to prefer simple and straightforward logic instead of using long and complex nested decision-making conditions.

Relational Operators:

The relational operators are used to form of decision making conditions. These are used to write condition expression that describe the relationship between two values i.e these operators allow us to compare two values to see whether they are equal to each other unequal or whether one is greater than the other or vive versa. Relational operators return the value 1(true) or 0(false). Don’t confuse the assignment operator (=) with the equals relational operator(==). The six relational operators in c/c++ are

Relational  operator meaning examples results
== Equal to (2==5)

(2==2)

False

True

< Less than (6<2)

(2<5)

(2<2)

False

True

False

> Greater than (10> 5)

(8>16)

(5>5)

True

False

False

<= Less than or equal to (10<=5)

(10<=10)

(2<=5)

False

True

True

>= Greater than or Equal to (10>=5)

(10 >= 10)

(10 >= 20)

True

True

False

!= Not Equal to (10 != 5)

(10 != 10)

True

false


Example: write a program in c++ which display the largest number using decision-making Relational operators:

#include <isotream.h>
#include <conio.h>
void main()
{
int a,b,c,max;
clrscr();
cout<<”Enter the 3 value :”;
cin>>a>>b>>c;
if(a>b)
    max=a;
else
    max=b;
if(c > max)
max= c;
cout<<”the  largest number is :”<<max;
getch();
}
Output:
Enter the 3 value : 35 68 10
the  largest number is : 68

Example: write a program in c++ which swap number using decision-making Relational operators:

#include <isotream.h>
#include <conio.h>
void main()
{
int a,b;
cout<<”Enter the 2 value :”;
cin>>a>>b;
if(a>b)
{
int temp=a;
a=b;
b=temp;
}
cout<<a<<””<<b;
getch();
}
Output:
Enter the 2 value : 4 8
8 4

Logical Operators decision-making :

More than one condition can be combined and tested in an if statement by connecting them with logical operator &&(AND),  ||(OR),  and ! (NOT). Such condition expression are referred to as Boolean expression complex or compound expression.

A compound expression with && logical expression is true of both of the relational expression are true otherwise it is false for examples:

If((marks > 70) &&  (marks < 80))

Cout<<”garde is A”;

Suppose if marks is 75 the expression ((marks >= 70) && (marks < 80)) is true if marks has the value  60 the expression ((marks >= 70) && (marks < 80)) is false.

The compound expression with (||) logical operation is true if any of the conditions is/are true and false only in the one case when all condition is false. For example:

If((choice == ‘Y’) || (choice == ‘y’))

goto top;

Thus the logical expression ((choice == ‘Y’) || (choice == ‘y’)) is true if either of the relational expressions is true otherwise it is false.

These definitions are summarized in the following truth table which displays app possible values for two decision-making conditions X and Y and the corresponding values of the logical expression.

 

X

 

 

Y

 

 

(X&&Y)

 

 

(X||Y)

 

true true true True
true False False True
False True False True
False False False False

the !(Not) operator is used for a different purpose than the && and || operators. It is used to reverse the meaning of a conditional expression rather than to combine simple conditional expression into compound conditional expressions in other words we can say that !(NOT) operator is used to negate an operand I.e changes true to false or false to true.

X !(X)
True False
False true

! (NOT) is called a prefix operator i.e it is always used in front of a condition but it is important to note that the condition must be enclosed in parentheses.


Example: write a program in c++ which display the employees insured using decision-making relational and logical operators:

#include <isotream.h>
#include <conio.h>
void main()
{
Char sex, status;
Int age;
Clrscr();
cout<<”Enter marital status married/unmarried(M/U):”;
cin>>status;
cout<<”Enter Sex(M/F) :”;
cin>>Sex;
cout<<”Enter Age:”;
cin>>age;
if((status == ‘M’) || (status == ‘U’) && sex== ‘M’ && age > 40) || (status == ‘U’ && sex == ‘F’ && age > 30) )
cout<<”employee is insured”;
else
    cout<<”Employee is not insured”;
getch();
}
Output:
Enter marital status married/unmarried(M/U): U
Enter Sex(M/F) : F
Enter Age: 35
Employee is insured

Operators and their Precedence:

The table below indicates the precedence order of all operators that we have discussed so far. The operators are listed here in order from the highest precedence to the lowest precedence.

  Operators         type
       ! Logical Not
       *  /  % Multiplication division and modulus
+  – Addition and Subtraction
<  >  <=  >= Relational operators
==   != Relational operators
&& Logical AND operator
|| Logical OR operator
= Assignment operator

 

Conditional operators or Ternary (?  : )

Conditional operator is the condensed form of an if-else decision-making statement for example

If(condition)

          Variable= exp1;

Else

          Variable= exp2;

The equivalent conditional expression is:

          (Condition) ? (exp1) : (exp2)

The question mark(?) and the colon (:) are use to form the conditional expression operator. The expression is read as if(condition) is true then the value returned to the target variable will be exp1 otherwise the value returned will be exp2 for example the assignment statement

Max = A > B ? A:Y;

Will assign the value of A to max if A>B otherwise it will assign the value of B to max.

Conditional expression is actually a ternary (three operands) operation in which condition exp1 and exp2 are the three operands and ? and : act as the operators.

a ternary operator in C++ is often called as the short end to the simple you find else so to use this ternary operator we can make use of two operators one is the question mark(?) and the Colin(:)  so the syntax of this ternary operator is first we should have to write the expression which should result in either true or false then we have to write this question mark and then the statement that we want to execute and just remember that we don’t need to add any semicolon here in the statement and then the Colin and then another statement and in the end add the semicolon so the  expression should evaluate to either true or false so depending on the expression the first or the second statement will be executed if the  expression is severity to true then the first statement will be executed and if the expression is evaluated to false then the second statement will be executed so to demonstrate that we’re going to write a ternary operator program.



Example: write a program in c++ which display even and odd number using decision-making conditional operator or ternary  (? : )  :

#include <isotream.h>
#include <conio.h>
void main()
{
Char sex, status;
int no;
cout<<”Enter the number :”;
cin>>no;
cout<<no<<”is”<< ((no % 2 == 0) ? “Even”:”odd”)
getch();
}
Output:
Enter the number : 6
6 is Even

Multiple Choice switch case / break  / default decision-making Statement:

We know that the goto statement is used to jump unconditionally to the indicated label. The if statement selects on of the two possible choices of action according to the value of a conditional expression. Whereas the multiple branching can be carried out in c/c++ by means of the switch statement.

A switch decision-making statement is a special form of multiple –alternative decision making i.e when multiple-choice possibilities are based on a single value the switch statement is the best choice. Actually switch statement is a more efficient way of representing nested-if statement. This statement is used to transfer control to a selected case of any one of the several indicated cases depending on the value of the switch expression. It has the following general from

Switch (expression)

{

          Case value1: statement(s);

                             Break;

          Case value2: statement(s);

                             Break;

`        :

          :

          Case valueN: statement(s);

                                      Break;

          Default:     statement(s);

}

Any legal c/c++ expression may be used in switch expression. It must be enclosed in parentheses and only used for equality test. Other relational operators or Boolean operators are not allowed. The expression value may be of type integer or character. The switch statement does not work with floating-point data types.

After evaluation of expression control is transferred directly to the statement whose case-value matches the result of the switch expression.

If no match is found control flow is transferred to the default statement. The default statement is optional. If no match is found and there is no default statement is present in the switch statement body control flow is transferred to the next statement following the switch statement body. However it is always a good idea to use a default statement in the switch structure. It may appear anywhere within the switch structure. It need not necessary be placed at the end.

The break statement is use to break switch statement i.e it is used to exit from a switch statement. It is used to transfer the control flow out of the entire switch statement to the first statement following the switch statement.it must be used at the end of every case statement if not execution will fall through to the next case statement. It has the following general format

break;

an integer or a character constant follows the reserved word ‘case’. Each value in each case must be different from all the others i.e the case values must be unique within a given switch statement.

If more than one statement are required to be executed in case body no need to enclose them within braces.


Example: write a program in c++ which display Vowel and Consonant character using decision-making switch case statement :

#include <isotream.h>
#include <conio.h>
void main()
{
char ch;
cout<<”Enter character : ”;
cin>>ch;
switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ‘u’:
cout<<”Vowel character”;
    break;
default: 
cout<<”Consonant character”;
}
getch();
}

Example: write a program in c++ which display Arithmetic operations using decision-making switch case statement :

#include <isotream.h>
#include <conio.h>
#include <math.h>

void main()
{
int a,b, ch;
clrscr();
cout<<”Enter number1”;
cin>>a;
cout<<”Enter number2”;
cin>>b;
cout<<endl;
Cout<<”which operation you perform on this number ”;
cout<<endl;
cout<<”1 for Addition”<<endl;
cout<<”2 for Subtraction ”<<endl;
cout<<”3 for Multiplication”<<endl;
cout<<”4 for Integer Division”<<endl;
cout<<”5 for Real Division ”<<endl;
cout<<”6 for Remainder”<<endl;
cout<<”7 for Exponent”<<endl;
cout<<”8 for Exit”<<endl<<endl;
cout<<”Enter your choice : ”;
cin>>ch;
switch(ch)
{
case 1:
cout<<”Sum = “<<(a+b);
    break;
case 2:
cout<<”Subtraction = “<<(a-b);
    break;
case 3:
cout<<”Product  = “<<(a*b);
    break;
case 4:
cout<<”Integer Division = “<<(a/b);
    break;
case 5:
cout<<”Real Division = “<<(float)(a+b);
    break;
case 6:
cout<<”Remainder = “<<(a%b);
    break;
case 7:
cout<<”Exponent = “<<(pow(a+b));
    break;
case 8: break;
default:
cout<<”you’ve selected a wrong option”

}
getch();

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button