Nested If and Logical Operator
Nested If and Logical Operator
Table of Contents
1.
Introduction
42
2.
42
3.
43
4.
Concept Map
43
4.1
4.2
4.3
4.4
4.5
43
43
44
45
46
5.
6.
7.
Nested-if statement
Logical-and (&)
Similarities and Differences for the use of nested-if and logical-and
Logical-or (||)
Logical-not (!)
53
5.1
5.2
53
53
54
6.1
6.2
54
54
55
56
56
Tools
Walk-through Task
6.2.1 Writing Code
6.2.2 Compilation
6.2.3 Executing the Program
Practice Tasks
57
7.1
7.2
7.3
7.4
7.5
57
57
57
58
58
Practice Task 1
Practice Task 2
Practice Task 3
Out comes
Testing
8.
59
9.
Evaluation criteria
59
10.
Further Readings
59
10.1
10.2
59
60
Books
Slides
60
P a g e | 41
Task No.
5.1
6.1
6.2
7
8
Total Time
20 mins
5 mins
15 mins
70 mins
60 mins
170 mins
P a g e | 42
4. Concept Map
We will introduce the nested-if condition and logical operators in this section. Furthermore, we will
study where and when to use these concepts in C++ program. When an if-statement is included within
another if-statement then we say that this is nested-if. For evaluating more than one condition, we can
use either nested-if or logical operators. There are three logical operators available in C++. For example
logical-and (&&), logical-or (||), and logical-not (!). We will study them one by one.
The nested-if statement is executed in the following way, first, the statement (percentage>=70 ) will
be evaluated, if the statement is true then the control is passed to the first statement within this ifstatement. The first line within this if-statement is again an if-statement, now the statement (age
<16) will be evaluated. Here if this statement is also true, then the student will be given the scholarship.
We can use logical-and to solve the same problem as well. This will be discussed in the next section.
To understand the above statement, revise your concepts from the previous course of ITC. The logicaland is evaluated as true if both values (conditions) are true. For revision, you can have a look on the
Department of Computer Science,
MAJU, 2016
P a g e | 43
Appendix A. For the above code, if both conditions are true, then the statement will be executed. The
difference between using logical-and and nested-if has been explained in the next section.
4.3 Similarities and Differences for the use of nested-if and logical-and
For the example used in the section 4.1 and 4.2, there is no difference, one can use any of them (nestedif or logical-and)
4.3.1 Scenario 1: Nested-if and Logical-and (&&) are similar
Code B:
if (percentage>=70 && age <16)
{
cout<<Congratulations! You are eligible for the scholarship;
}
In this scenario, both codes will output the same. However, there are certain differences in using
nested-if and logical-and (&&). There are some scenarios where use of nested-if is better, however,
there are some other scenarios where the use of logical-and(&&) is better. For example, consider the
following case.
4.3.2 Scenario 2: Nested-if is better than Logical-and (&&)
P a g e | 44
However, you probably, will not like to write the above code in the following way.
if (percentage>=70 && age <16)
{
cout<<Congratulations! You are eligible
scholarship;
}
if (percentage>=70)
{
cout<<Your percentage is more than 70;
}
for
the
the
P a g e | 45
refresh your concepts of logical operators by looking into the appendix A available at the end of this lab.
In the logical-or (||), the condition is considered as true if any of the conditions are true. For example,
re-writing the previous example with logical-or (||) would look like the following
if (percentage>=70 || age <16)
{
cout<<Congratulations!
scholarship;
}
You
are
eligible
for
the
The cout statement will be executed if any of the conditions is true. For example either the person has
achieved more than 70% marks or his/her age is less than 16, the scholarship will be awarded to that
person.
the above statement will be evaluated as false because the condition (5==5) is evaluated as true and
logical-not (!) will make it false, as the if-statement is evaluated as false, therefore, the cout-statement
will not be executed. Similarly, we have written the previously discussed example by incorporating
logical-not (!)
if (percentage>=70 && (!(age <16)))
{
cout<<Congratulations!
scholarship;
}
You
are
eligible
for
the
Now we have both logical-and and logical-not. You know that logical-and will be evaluated as true if
both conditions are true. The first condition would be true when percentage is more than or equal to 70,
however, the second condition would be true when the age is more than or equal to 16. Remember,
from previous discussion that whenever the inner condition (age<16) is false, the logical-not (!) will
make it true. Therefore, the scholarship will be given to only those students whose percentage is greater
than or equal to 70 and whose age is more than or equal to 16.
P a g e | 46
switch statement is used to p ick from number of alternatives provided by the system. The general
syntax of the switch statement is as follows:
switch (expression)
{
case value1:
statements
break;
case value2:
statements...
break;
.
.
.
case valuen:
statements
break;
default:
statements.
}
Where switch, case, break, and default are the reserve words and have particular meanings which you
will learn in this lab. Please note that the break statement is an optional statement. This means you can
use this statement or not depending upon the situation. You will learn the effect of including and
excluding a break statement in the next section.
The expression sometimes, is referred to, selector. First the expression in the switch statement is
evaluated. Subsequently, the corresponding case is executed. It is not mandatory that the expression is
an identifier. It can be a identifier or an expression. However, the value of the expression should be
integral only.
In this section, we will give a basic example of switch statement with and without the break statement.
Consider that we want to print the following output where user have multiple options, out of which the
user can pick one option to be executed at one time.
Enter 1 to purchase products
Enter 2 to sale products
Enter 3 to see the profit statement =
In such a menu driven statement, using switch statement is encouraged. This will make your code more
readable.
You can program this problem using the following code:
int option;
cout<< Enter 1 to purchase products;
Department of Computer Science,
MAJU, 2016
P a g e | 47
When user enters the value 1, the user will get the following output:
You selected the option to purchase products
When user enters the value 2, the user will get the following output:
You selected the option to sale products
When user enters the value 3, the user will get the following output:
You selected the option to see the profit statement
However, consider that if we exclude the break statement (recall from the previous section that the
break statement is optional), then the output will be changed for different inputs. For example: consider
the following code without break statements.
int option;
cout<< Enter 1 to purchase products;
cout<< Enter 2 to sale products;
cout<< Enter 3 to see the profit statement =;
cin>>option;
switch (option)
{
case 1:
cout<<You selected the option to purchase products;
case 2:
cout<<You selected the option to sale products;
case 3:
cout<<You selected the option to see the profit statement;
P a g e | 48
default:
cout<<You have selected the wrong value;
}
When user enters the value 1, the user will get the following output:
You selected the option to purchase products
You selected the option to sale products
You selected the option to see the profit statement
When user enters the value 2, the user will get the following output:
You selected the option to sale products
You selected the option to see the profit statement
When user enters the value 3, the user will get the following output:
You selected the option to see the profit statement
When the break statement is not included then from onward a true case, all cases will be executed until
the switch statements ends, or a break occurs. For example consider the following example, for more
clarification.
int option;
cout<< Enter 1 to purchase products;
cout<< Enter 2 to sale products;
cout<< Enter 3 to see the profit statement =;
cin>>option;
switch (option)
{
case 1:
cout<<You selected the option to purchase products;
case 2:
cout<<You selected the option to sale products;
break;
case 3:
cout<<You selected the option to see the profit statement;
default:
cout<<You have selected the wrong value;
}
In this switch statement, we have written a break statement after the statement associated with case 2.
When user enters the value 1, the user will get the following output:
You selected the option to purchase products
You selected the option to sale products
Department of Computer Science,
MAJU, 2016
P a g e | 49
The user will not get the output You selected the option to see the profit statement
because there is a break after second case.
When user enters the value 2, the user will get the following output:
You selected the option to sale products
The statement cout<<You selected the option to see the profit statement will not be
executed because there is a break after the second case.
Finally, when user enters the value 3, the user will get the following output:
You selected the option to see the profit statement
If user enters any statement other than 1, 2, or 3 (for which we have written cases), in that case, the
default statement is executed.
4.6.2
We learned in the previous section that the value of the expression could be an integral. In the previous
example, you have learned how integer values are used in the switch statement. Now we will learn how
the character values can be used in the switch statement. Consider the following example; consider you
want to make a program that converts Pakistani Rupee into different international currencies such as:
Euro, Dollar, and Riyal.
char option;
cout<<Enter character E to change Rupee into equivalent value in Euro;
cout<<Enter character D to change Rupee into equivalent value in dollar;
cout<<Enter the character R to change Rupee into equivalent value in Riyal;
cin>>option;
switch(option)
{
case E:
cout<<You selected the conversion from Rupee to Euro;
break;
case D:
cout<<You selected the conversion from Rupee to Dollar;
break;
case R:
cout<<You selected the conversion from Rupee to Riyal;
break;
default:
cout<<Wrong input;
}
P a g e | 50
2) The program will work fine for the upper case characters only. If user enter d in lowercase
rather than upper case, then the program will output cout<<Wrong input;. To tackle
both uppercase and lowercase character, you can write the following code:
switch(option)
{
case E:
case e:
cout<<You selected the conversion from Rupee to Euro;
break;
case D:
case d:
cout<<You selected the conversion from Rupee to Dollar;
break;
case R:
case r:
cout<<You selected the conversion from Rupee to Riyal;
break;
default:
cout<<Wrong input;
}
For the better understanding of this program, remember, the discussion on the break statement in the
previous section.
4.6.3
In the expression of the switch statement, one can use relation operators which will be evaluated as
true of false, for example consider the following example followed by a discussion on it.
int marks;
cout<< Enter your marks;
cin>>marks;
switch(marks>=50)
{
case 1:
cout<<Congratulations, you have qualified the examination;
break;
case 0:
cout<<Sorry, you have not qualified the examination ;
break;
}
In this case, the expression will be evaluated as logical-true or logical-false. If the marks are greater than
or equal to 50, then the statement
cout<<Congratulations, you have qualified the
examination; will be executed, otherwise, the statement cout<<Sorry, you have not
qualified the examination ; will be executed. As the expression is logical-true or logical-false,
therefore, you can use true instead of 1 and false instead of 0 as shown below.
int marks;
Department of Computer Science,
MAJU, 2016
P a g e | 51
In the previous section, you have learned how an integer, character, and relational operator can be used
in the expression of switch statement, however, in this section, you will experience that the use of
complex expression is allowed in the switch statement. Consider the following example. The user enters
a number and program finds the digit at unit place and displays it.
int value;
cin>>value;
switch (value%10)
{
case 0:
cout<<The
break;
case 1:
cout<<The
break;
case 2:
cout<<The
break;
case 3:
cout<<The
break;
case 4:
cout<<The
break;
case 5:
cout<<The
break;
case 6:
cout<<The
break;
case 7:
cout<<The
break;
case 8:
cout<<The
break;
case 9:
cout<<The
P a g e | 52
break;
}
2. Write a program which asks the user to either convert the number of days into hours or
minutes. Based on the option entered by user your program should calculate the result
accordingly.
Based on the option entered by user, your program should calculate and display the results
accordingly.
P a g e | 53
6.2
Walk-through Task
In this specialized task, you will learn that how the practice task 2 of third lab can be achieved with the
help of nested-if statement.
Write a program which would calculate the grades of students against their score. The grading criteria is
as follows:
>= 90
>=80
>=70
>=60
<60
A
B
C
D
grade
grade
grade
grade
F grade
P a g e | 54
P a g e | 55
6.2.2 Compilation
After writing the code, now you are ready to compile it. For compilation, select Build Solution from the
Build option in the menu bar as shown in the Figure 2.
..
Figure 2: Compiling the C++ program
.
When you click on build solution, the compiler would start processing your program. The progress of
build activity would be displayed on the output window as shown in the Figure 3.
The progress would show whether the build was successful or not. It would display the errors if any.
Otherwise it would display the message Build succeeded.
6.2.3 Executing the Program
Now run the program by pressing Ctrl+F5 from keyboard or selecting play option from Debug menu
(Debug menu can be accessed from the Figure 2). When you press Ctrl+F5, the compiler would start
executing the program and would display the final output to your screen as shown in the Figure 4.
P a g e | 56
7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to
finish the tasks in the required time. When you finish them, put these tasks in the folder specified by
your lab instructor
Write a program which would calculate the sales tax on two products by the name of Conditioner and
Facewash. First the user would be asked for the product type. Once the user selects the product then
ask him/her about the price of the product. For the product Conditioner, If the price is greater than 100
and less than 800 then calculate 5% sales tax, and for the product Facewash, , If the price is greater than
150 and less than 500 then calculate 10% sales tax on the product. Then display the sales tax to the user.
Note: Use nested-if to achieve this task.
Write a program which asks the user to open a bank account either Current or Savings. Your program
will display the following menu at the start:
Press 1 for Current Account
Press 2 for Savings Account
On the selection of account type, the user will open an account by providing an initial amount. In current
account the initial amount for opening an account would be 2000 and for savings it would be 5000. After
choosing the account type and opening the account with initial amount, your program will display the
following menu:
Press a for Deposit the money
Press b for withdrawing the money
In current account the user cannot withdraw more than 10000 rupees. In Savings account the user
cannot withdraw more than 25000. When the user withdraws amount make sure that amount should
not be more than the balance in account and at the end of withdrawal transaction, there should be
minimum of 500 rupees for each account.
Write a program in which a father wants to know the grade of his two sons. Ask the user for the marks.
If the marks are greater than 90 then he/she receives A grade. If his first son gets an A grade then he will
be give a treat by his father. If the second son gets an A grade then he would be given a treat by his
Department of Computer Science,
MAJU, 2016
P a g e | 57
father. If both sons get A grade then both of them will get a treat from their father. Use nested if-else to
do this task.
[Expected time = 15 mins]
Write a program which will read two numbers and would display the following menu to the user:
Press 1 to find the numbers are divisible by 2
Press 2 to add the two numbers
Press 3 to subtract the two numbers
Press 4 to multiply the two numbers
Press 5 to divide the two numbers
Press 6 to find whether the numbers are odd or even
Note: All the above operations would be applied on both the numbers that user reads.
7.7 Testing
For the tasks mentioned in Section 7, following are the test cases. The instructor will check the outputs
of the practice tasks accordingly.
Table 2: Testing of Practice Tasks
Practice
Tasks
6.2
Sample Input
Sample output
Grade is: B
Confirmation
P a g e | 58
Marks:85
Marks:65
Marks:40
Marks: 60
Grade is: D
Grade is: F
Grade is: D
7.1
7.2.1
Account Type: 1
Amount: 2000
Deposit Amount: 1000
Withdraw amount: 1500
Account Type: 2
Amount: 5000
Deposit Amount: 500
Withdraw amount: 5400
Withdraw amount : 4500
7.2.2
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).
Table 3: Evaluation of the Lab
Sr. No.
1
2
3
4
5
6
Task No
5.1
5.3
7
8
Description
Problem Modeling
Home work
Practice tasks and Testing
Evaluation Tasks (Unseen)
Comments
Good Programming Practices
Marks
20
10
35
20
5
10
Reference Books:
1. Beginning C++, the complete language, by Ivor Horton, Wrox Publishers.
2. How to Program in C++, Dietel and Dietel
P a g e | 59
10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$
|| OPERATOR
! OPERATOR
a && b
a || b
!a
true False
False True
P a g e | 60