$24
Objectives:
Learn Increment and decrement operator.
Learn Arithmetic, Relational and Logical operators.
Learn if Statement.
Learn if else Statement.
Learn nested if Statement.
Learn nested if-else Statement.
Increment and Decrement Operators:
The increment and decrement operators are unary operators that can be applied to an integer variable. For example, assuming the variables are of type int, the following three statements all have
exactly the same effect:
count = count + 1;
count += 1;
++count;
The preceding statements each increment the variable count by 1. The last form, using the increment operator, is clearly the most concise. The action of this operator is different from the other operators that you’ve seen, in that it directly modifies the value of its operand. The effect in an expression is to increment the value of the variable and then to use that incremented value in the expression. For example, suppose count has the value 5, and you execute this statement:
total = ++count + 6;
The increment and decrement operators are of higher precedence than all the binary arithmetic operators. Thus, count will be first incremented to the value 6, and then this value will be used in the evaluation of the expression on the right side of the assignment operation. The variable total will therefore be assigned the value 12. We use the decrement operator in the same way as the increment operator:
total = --count + 6;
Assuming count is 6 before executing this statement, the decrement operator will reduce it to 5, and this value will be used to calculate the value to be stored in total, which will be 11.
Relational and equality operators (==, ! =, , <, =, <=):
In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result. We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++:
==
Equal to
!=
Not equal to
Greater than
<
Less than
=
Greater than or equal to
<=
Less than or equal to
Write each statements in a C++ program and evaluate the result as true or false, initialize variable int a = 2, b = 3, c = 6;
(7 == 5)
(54)
(3 != 2)
(6 = 6)
c = b – a
a == c + b – c
(a*b = c)
(b+4 a*c)
(a + b / 2) <= c
((b=2) == a)
Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.
Logical operators (!, &&, || ):
The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing
false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.
For example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
The logical operators && and || are used when evaluating two expressions to obtain a single relational result.
The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true and false otherwise. The following panel shows the result of operator && evaluating the expression a && b:
OPERATOR
The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:
|| OPERATOR
a
B
a && b
true
True
true
true
false
true
false
True
true
false
false
false
For example:
( (5 == 5) && (3 6) ) // evaluates to false ( true && false ).
( (5 == 5) || (3 6) ) // evaluates to true ( true || false ).
Write each statements in a C++ program and evaluate the result as true or false, initialize variable a = 5, b = 10, c = 15 and flag =1.
c == a+b || ! flag
a != 7 && flag || c = 6
! (b <= 12) && a % 2 == 0
! (a 5 || c < a + b)
Selection Statements:
if-statement:
Used to execute a statement or a compound_statement when a condition is true.
Single statements
Compound statements
if(condition)
if(condition)
statement1;
compound_statement1
Execute statement1 if condition is true
Execute compound_statement1 if condition is true
cout<<“Enter a number: “;
cout<<“Enter a number: “;
cinnum; if (num 0)
cinnum; if (num 0)
cout<<“you entered positive
{ cout<<“you entered positivenumber”;
number”;
cout<<”the number is greater than
0”;
}
Example: Finding max of three numbers
Example:
max = num1;
cinaccountType; // s = saving
if(num2 max)
if(accountType == 's' || accountType == 'S')
max = num2;
{
if(num3max
cout<< "Enter positive amount ";
)
cinamount;
max = num3;
balance = balance + amount;
}
*A compound statement consists of zero or more statements enclosed in curly braces ({ }). A compound statement can be used anywhere a statement is expected. Compound statements are commonly called "blocks."
if-else statement:
An if-else statement is used to execute a statement or a compound-statement when a condition is true; and another statement or compound-statement when that condition is false.
Single statements
Compound statements
if(condition)
if(condition)
statement1;
compound_statement1
else
else
statement2;
compound_statement2
Execute statement1 if condition is true else
Execute compound_statement1 if condition is
execute statement2
true else execute compound_statement2
Note:
It is a syntax error to put a semicolon after the
closing brace of compound_statement1
A
compound statement may contain zero or
more statements
Example: Finding max of two numbers
if(x= y)
max = x;
else
max = y;
Example:
cinaccountType; // s = saving if(accountType == 's' || accountType == 'S')
{
cout<< "Enter positive amount "; cinamount;
balance = balance + amount;
}
else
cout<<"Wrong currency type";
Nested if statements:
The compound statement in an if-branch may contain one or more of any type of if-statement discussed above.
Example:
if(hours < 9)
if(distance 500)
cout<<"Type 01";
else
cout<<"Type 02";
is equivalent to:
if(hours < 9){
if(distance 500)
cout<<”Type 01";
else
cout<<"Type 02";
}
Note: In a nested if statement, the last else is associated with the closest unpaired if, unless braces are used to alter the default pairing
Nested if-else statements:
The compound statement in an if-branch or an else-branch of an if-statement may contain one or more of any type of if-statement discussed above.
Example:
if(grade < 0.0 || grade 100.0)
cout<<"Error: Invalid grade";
else
{
if(grade = 80.0)
letterGrade='A';
else if(grade = 70.0)
letterGrade = 'B';
else if(grade = 60.0)
letterGrade = 'C';
else if(grade = 50.0)
letterGrade = 'D';
else letterGrade = 'F';
cout<<"The letter grade
is"<<letterGrade;
}
Nested if else structures can be complicated:
if(condition1){
statement1;
if(condition2)
statement2;
else
statement3;
statement4;
}
else{
if(condition3)
compound_statementA
else if(condition4)
compound_statementB
else
compound_StatementC
compound_StatementD
}
Lab Tasks:
Q1: Write a program which accepts a character and display its next character.
Q2: Write a program that inputs a number and check if it is divisible by 2, 3 or 5. If it is not divisible by any of them than simply display not divisible by any of them.
Q3: Create a program that converts inches to feet-and-inches— for example, an input of 77 inches should produce an output of 6 feet and 5 inches. Prompt the user to enter an integer value corresponding to the number of inches, and then make the conversion and output the result. (Hint: Use a variable to store the inches-to-feet conversion rate; the modulus operator will be very helpful.)
Q4: Compute and print a water bill in Rupees, given an unpaid balance, previous and current meter reading in gallons. Bill includes a demand charge of Rs. 350, a use charge of Rs. 100 per thousand gallons, and a surcharge of Rs. 50 if there is unpaid balance.
Q5: Suppose you want to associate noise loudness measured in decibels with the effect of the noise. The following table shows the relationship between noise levels and human perceptions of noises.
Loudness in Decibels (db)
Perceptions
50 or lower
quite
51-70
intrusive
71-90
annoying
91-110
very annoying
Above 110
uncomfortable
Get the noise level from the user and print the human perception accordingly.
Q6: The department of Defense would like a program that identifies single males between ages of 18 and 26, inclusive. One way to do this to use a nested if statement whose conditions test the next criterion only if all previous criteria tested were satisfied.
Programming Fundamentals
Lab 3: Operators, Expressions
Riphah International University
Faculty of Computing