100% found this document useful (1 vote)
15 views24 pages

Expressions&Operators Prog

This document provides an overview of expressions and operators in C++, detailing the various types of operators such as arithmetic, logical, relational, and bitwise operators. It explains their functions, syntax, and precedence, along with examples of how to use them in C++ programming. The document also highlights the differences between prefix and postfix increment/decrement operators and the evaluation of expressions with multiple operators.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
15 views24 pages

Expressions&Operators Prog

This document provides an overview of expressions and operators in C++, detailing the various types of operators such as arithmetic, logical, relational, and bitwise operators. It explains their functions, syntax, and precedence, along with examples of how to use them in C++ programming. The document also highlights the differences between prefix and postfix increment/decrement operators and the evaluation of expressions with multiple operators.

Uploaded by

onetechet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Lecture Five - Expressions & Operators in C++ C++ Programming Language

Lecture Five - Expressions & Operators


in C++
What are C++ operators?
In programming context, an operator is a symbol or keyword that instructs a compiler to evaluate
mathematical or logical expressions. In addition to mathematical operators, most programming
languages support special operators some of which are English-like keywords. Given that C++ is a
system programming language; most of its operators are special symbols available on a standard
keyboard. This makes the language more portable, and internationally accepted because its syntax does
not rely a lot on natural languages like English.

Classification of C++ Operators


Operators in C++ are grouped into several categories including:-
 Arithmetic,
 Logical,
 Relational,
 Bitwise, and
 Assignment operators.
 Arithmetic Operators
There are many operators for manipulating numeric values and performing arithmetic operations. C++
offers a multitude of operators for manipulating data. Generally, there are three types of operators:
 unary operators, only require a single operand.
 binary operators, work with two operands.
 ternary operators, require three operands.

Arithmetic operators perform basic mathematical operations such as addition, subtraction,


multiplication, division, modulus, and increment/decrement. They typically compute these calculations
between variables or values in C++ programs.

1
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 Addition (+)

The addition operator adds two operands or values together.


Example:
#include <iostream>
int main() {
int x=5, y=7;
int result = x+y;
cout <<"The result of "<< x <<" + "<< y <<" is "<< result << endl;
return 0;}
Output: The result of 5 + 7 is 12

 Subtraction (-)

The subtraction operator subtracts the right operand from the left operand.
Example:
#include <iostream>
int main() {
int x=10, y=5;
int result = x-y;
std::cout << "The result of " << x << " - "<< y <<" is "<< result <<
std::endl;
return 0; }
Output: The result of 10 - 5 is 5

 Multiplication (*)

The multiplication operator multiplies two operands together.


Example:
#include <iostream>
int main() {
int x=4, y=3;
int result = x*y;
cout << "The result of " << x << " * " << y <<" is "<< result << endl;
return 0;
}
Output: The result of 4 * 3 is 12

 Division (/)

The division operator divides the left operand by the right operand.
Example:
#include <iostream>
int main() {
int x=10, y=2;
int result = x/y;
cout <<"The result of "<< x <<" / "<< y <<" is "<< result << endl;
2
Lecture Five - Expressions & Operators in C++ C++ Programming Language
return 0;}
Output: The result of 10 / 2 is 5

 Modulus (%)

Example:
#include <iostream>
int main() {
int x=10 y=3;
int result = x%y;
cout <<"The result of "<< x <<" % "<< y <<" is "<< result << std::endl;
return 0; }
Output:
The result of 10 % 3 is 1

C++ Program

 Increment (++)
The increment operator adds 1 to the value of the variable.
Example:
#include <iostream>
int main() {
int x=5;
x++;
cout << "The value of x is now "<< x << endl;
return 0; }
Output: The value of x is now 6

3
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 Decrement (--)
The decrement operator subtracts 1 from the value of the variable.
Example:
#include <iostream>
int main() {
int x=5;
x--;
cout <<"The value of x is now "<< x << endl;
return 0; }
Output: The value of x is now 4

One characteristic of ++ and -- operators is that they can be used as prefix and suffix. This means that,
an operator can be written either before the variable e.g. ++count or after it as in, count++. The
prefix increments the value, and then fetch it while postfix fetches the
value first, then increments the original. For example, if x is 5 and you write:
int a = ++x;
The statement increments x to 6, and then fetches the value to assign it to a. The resulting value of a is
6 and that of x is also 6. If, after doing this operation, you write:
int b = x++;
The statement fetches the value in x. i.e., 6 and assigns it to b, then it goes back to increment x. Thus,
the new value of b is 6, and that of x is 7.

The difference becomes apparent when you look at the value of the expression;

 ++i means that the value of i has already been incremented by 1,


 whereas the expression i++ retains the original value of i.
 This is an important difference if ++i or i++ forms part of a more complex expression:
 ++i i is incremented first and the new value of i is then applied,
 i++ the original value of i is applied before i is incremented.
 The decrement operator -- modifies the operand by reducing the value of the operand
by 1.

Effect of increment / Decrement Notations


#include <iostream>
using namespace std;
int main(){
int i = 2, j = 8;
cout << i++ << endl; // Output: 2
cout << i << endl; // Output: 3
cout << j-- << endl; // Output: 8
cout << --j << endl; // Output: 6
return 0;}

4
Lecture Five - Expressions & Operators in C++ C++ Programming Language
#include <iostream>
int main() {
int x1 = 1, y1 = 10,x2 = 100, y2 = 1000;
cout <<"x1=" << x1 << ", y1=" << y1
<<", x2=" << x2 << ", y2=" << y2 << '\n';
y1 = x1++;
cout <<"x1=" << x1 << ", y1=" << y1
<<", x2=" << x2 << ", y2=" << y2 << '\n';
y2 = ++x2;
cout <<"x1=" << x1 << ", y1=" << y1
<<", x2="<< x2 << ", y2=" << y2 << '\n';
}

How is an expression with multiple operators evaluated?

Example: float val =5.0; cout << val++ – 7.0/2.0;

 Operator precedence determines the order of evaluation, i.e. how operators and operands
are grouped.
 ++ has the highest precedence and / has a higher precedence than -.
 The example is evaluated as follows:
 (val++) – (7.0/2.0). The result is 1.5, as val is incremented later.
 If two operators have equal precedence, the expression will be evaluated:

Example: 3 * 5 % 2 is equivalent to (3 * 5) % 2, the result is 1.

 Logical operators

Logical operators perform logical operations on Boolean expressions (expressions that evaluate to
either true or false). There are three logical operators in C++:

5
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 AND (&&)
The AND operator returns true if both operands are true, and false otherwise.
Example:
#include <iostream>
int main() {
bool x=true, y=false;
bool result = x&&y;
cout<<"The result of "<<x<<" && "<<y<<" is "<<boolalpha<<result<<endl;
return 0; }
Output: The result of 1 && 0 is false
 OR (||)
The OR operator returns true if at least one of the operands is true, and false otherwise. Example:
Example:
#include <iostream> int main() {
bool x=true, y=false;
bool result=x||y;
cout << "The result of "<< x <<" || "<< y <<" is "<< boolalpha << result
<<
endl;
return 0;}
Output: The result of 1 || 0 is true
 NOT (!)
The NOT operator returns the opposite of the Boolean value of the operand.
Example:
#include <iostream>
int main() {
bool x=true;
bool result=!x;
cout << "The result of !"<< x <<" is "<< boolalpha << result << endl;
return 0; }
Output: The result of !1 is false

// C++ program demonstrating && operator truth table


#include <iostream>
using namespace std;
int main() {
int a = 5;
int b = 9;
// false && false = false
cout << ((a == 0) && (a > b)) << endl;
// false && true = false
cout << ((a == 0) && (a < b)) << endl;
// true && false = false
cout << ((a == 5) && (a > b)) << endl;
// true && true = true
cout << ((a == 5) && (a < b)) << endl;
return 0;}
6
Lecture Five - Expressions & Operators in C++ C++ Programming Language
Output:
0
0
0
1

 Relational operators
There are six relational operators supported in C++: equals (==), less than (<), greater than (>), less
than or equal to (<=), greater than or equal to (>=), and not equals (!=). Like arithmetic operators,
relational operators are also binary operators because they act on two operands e.g. 5>3 to return
true or false.

Example:
#include <iostream>
int main() {
int x=4, y=3;
cout <<x==y<< endl;
cout <<x!=y<< endl;
cout <<x>y<< endl;
cout <<x<y<< endl;
return 0; }
Precedence of Relational Operators
Relational operators have lower precedence than arithmetic operators but higher precedence than
assignment operators
Example: bool flag = index < max – 1;
In our example, max – 1 is evaluated first, then the result is compared to index, and the value of the
relational expression (false or true) is assigned to the flag variable.

7
Lecture Five - Expressions & Operators in C++ C++ Programming Language

Similarly, in the following Example:


int result;
result = length + 1 == limit;
length + 1 is evaluated first, then the result is compared to limit, and the value of the relational
expression is assigned to the result variable. Since result is an int type, a numerical value is assigned
instead of false or true, i.e. 0 for false and 1 for true. It is quite common to assign a value before
performing a comparison, and parentheses must be used in this case.
Example: (result = length + 1) == limit
Our example stores the result of length + 1 in the variable result and then compares this expression
with limit.
Operands and Order of Evaluation
The operands for Boolean type operators are of the bool type. However, operands of any type that
can be converted to bool can also be used, including any arithmetic types. In this case the operand is
interpreted as false, or converted to false, if it has a value of 0. Any other value than 0 is interpreted as
true.
Example: (length < 0.2) || (length > 9.8) is true if length is less than 0.2 or greater than 9.8.
Example: (index < max) && (cin >> number) is true, provided index is less than max and a number is
successfully input. If the condition index < max is not met, the program will not attempt to read a
number!
One important feature of the logical operators && and || is the fact that there is a fixed order of
evaluation. The left operand is evaluated first and if a result has already been ascertained, the right
operand will not be evaluated! The NOT operator ! will return true only if its operand is false. If the
variable flag contains the value false (or the value 0), !flag returns the Boolean value true. The &&
operator has higher precedence than ||. The precedence of both these operators is higher than the
precedence of an assignment operator, but lower than the precedence of all previously used operators.
The ! operator is a unary operator and thus has higher precedence. The && operator has higher
precedence than ||. The precedence of both these operators is higher than the precedence of an
assignment operator, but lower than the precedence of all previously used operators. The ! operator is
a unary operator and thus has higher precedence.

What if I want to know if a value is in a range? Test for: 100 ≤ L ≤ 1000? What if I want to know if a
value is in a range? Test for: 100 ≤ L ≤ 1000?
if(100 <= L <= 1000)
{
cout<<“Value is in range…\n”);
}
if((100 <= L) <= 1000)
{ cout<<“Value is in range…\n”); }
C ++ Treats this code this way

8
Lecture Five - Expressions & Operators in C++ C++ Programming Language

Suppose L is 5000. Then 100 <= L is true, so (100 <= L) evaluates to true, which, in C, is a 1. Then it
tests 1 <= 1000, which also returns true, even though you expected a false.

Want to check whether -3 <= B <= -1 Since B = -2, answer should be True (1) But in C++, the
expression is evaluated as
((-3 <= B) <= -1) (<= is left associative)
(-3 <= B) is true (1)
(1 <= -1) is false (0)
Therefore, answer is 0!
Solution (not in C): (-3<=B) and (B<=-1) In C++: (-3<=B) && (B<=-1).

( ((A + B) > 5) && ( ((A=0) < 1) > ((A + B) – 2)) )


( (6 > 5) && ( ((A=0) < 1) > ((A + B) – 2)) )
( 1 && ( ( 0 < 1) > ((A + B) – 2)) )
( 1 && ( 1 > ( 2 – 2) ))
( 1 && ( 1 > 0 ) )
( 1 && 1 )
Answer: 1

 Bitwise Operators

Bitwise operators perform bitwise operations on the binary representations of integers. They
manipulate the individual bits in the binary representation of a number, rather than the whole
number itself. The truth tables for &, |, and ^ are as follows:

9
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 Bitwise AND (&)

The bitwise AND operator compares each bit of two numbers and sets the resulting bit to 1 only if
both bits are 1.
Example:
#include <iostream>
int main() {
int a=12;// binary: 1100
int b=25;// binary: 11001
int result=a&b;
cout <<"Result: "<< result << endl; }
Output: Result: 8

 Bitwise OR (|)

The bitwise OR operator compares each bit of two numbers and sets the resulting bit to 1 if either bit
is 1.
Example:
#include <iostream>
int main() {
int a=12;// binary: 1100
int b=25;// binary: 11001
int result=a|b;
cout <<"Result: "<< result << endl; }
Output: Result: 29

 Bitwise XOR (^)


10
Lecture Five - Expressions & Operators in C++ C++ Programming Language

The bitwise XOR operator compares each bit of two numbers and sets the resulting bit to 1 only if one
of the bits is 1.

Example:
#include <iostream>
int main() {
int a=12;// binary: 1100
int b=25;// binary: 11001
int result=a^b;
cout <<"Result: "<< result << endl; }
Output: Result: 21

 Bitwise NOT (~)


The bitwise NOT operator will reverse the bits of a number.
Example:
#include <iostream>
int main() {
int a=12;// binary: 1100
int b=25;// binary: 11001
int result=~a;
cout <<"Result: "<< result << endl; }
Output: Result: -13

11
Lecture Five - Expressions & Operators in C++ C++ Programming Language

Left shift (<<)


The left shift operator shifts the bits of a number to the left by a specified number of positions.
Syntax
a >> b;
where,
a is the integer value to be shifted.
b specifies how many positions to shift the bits.

Example:
#include <iostream>
int main() {
int a=12;// binary: 1100
int b=25;// binary: 11001
int result=a<<2;
cout <<"Result: "<< result << endl; }
Output: Result: 48

 Right Shift(>>) Operators


Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first operand,
and the second operand decides the number of places to shift.
Syntax
a >> b;
where,
a is the integer value to be shifted.
b specifies how many positions to shift the bits.

 Assignment Operators

12
Lecture Five - Expressions & Operators in C++ C++ Programming Language

Assignment operators assign a value to a variable. These operators can be combined with arithmetic
operators to perform an operation and assign the result to a variable in a single step.

 Assignment (=)
The assignment operator assigns causes the operand on the left side of the assignment operator to
have its value changed to the value on the right side of the operator.
Example:
#include <iostream>
int main() {
int x=5, y;
y = x;
cout <<"The value of y is "<< y << endl;
return 0; }
Output: The value of y is 5

The most important rule when assigning is the right-to-left rule: Assignment operation always takes
place from right to left, and never the other way round. The following statement is invalid!
5 = students;

 Compound Assignment Operators


C++ has a unique way of combining arithmetic and assignment operators compound operators
typically referred to as self-assigned operators. The most commonly used self-assigned operators are
conditional addition (+=), subtraction (-=), division (/=), multiplication (*=), and modulus (%=).

13
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 Left shift assignment (<<=)

The left shift operator shifts the bits of the left operand leftwards by the number of positions specified
in the right operand and assigns the result back to the left operand.
Example:
#include <iostream>
int main() {
int x=5
x<<=3;
cout <<"The value of x is "<< x << endl;
return 0; }
Output: The value of x is 40

 Right shift assignment (>>=)

The right shift operator shifts the bits of the left operand rightwards by the number of positions
specified in the right operand and assigns the result back to the left operand.
Example:
14
Lecture Five - Expressions & Operators in C++ C++ Programming Language
#include <iostream>
int main() {
int x=5
x>>=3;
std::cout <<"The value of x is "<< x << std::endl;
return 0; }
Output: The value of x is 5

 Bitwise AND assignment (&=)

This operator performs a bitwise AND operation on the left and right operands and assigns the result
back to the left operand.
Example:
#include <iostream>
int main() {
int x=5
x&=3;
cout <<"The value of x is "<< x << endl;
return 0; }
Output: The value of x is 1

 Bitwise OR assignment (|=)

This operator performs a bitwise OR operation on the left and right operands and assigns the result
back to the left operand.
Example:
#include <iostream>
int main() {
int x=5
x|=3;
std::cout <<"The value of x is "<< x << std::endl;
return 0; }
Output: The value of x is 7

 Bitwise XOR assignment (^=)

This operator performs a bitwise XOR operation on the left and right operands and assigns the result
back to the left operand.
Example:
#include <iostream>
int main() {
int x=5
x^=3;
cout <<"The value of x is "<< x;
return 0; }
Output: The value of x is 6

15
Lecture Five - Expressions & Operators in C++ C++ Programming Language

 Conditional/Ternary Operator

The conditional operator represented by a question marks and colon is the only ternary operator in
C++ that takes three operands. The operator evaluates an expression returning a value if the
expression after (?) is true, or the expression following (:) if the condition returns false. The general
format of the statement is:
variable = Expression1 ? Expression2 : Expression3;

Example:
// C++ program to find largest among two numbers using ternary operator
#include <iostream>
int main(){
int m = 5, n = 4;
(m > n) ? cout<<”m is greater than n that is”<<m;
: cout<<”n is greater than n that is”<<n;
return 0;}

 Miscellaneous Operators
C++ supports other miscellaneous operators such as sizeof, cast, address of, and scope resolution
operator.
 The size of operator
The sizeof operator is an inbuilt function that accepts one parameter and returns the size in bytes. For
example, the following statement assigns 8 to memsize because a double has 8 bytes:
memsize = sizeof (double);

Example:
// C++ Program To demonstrate sizeof operator
#include <stdio.h>
int main(){
cout<<“Size of char: "<< sizeof(char);
cout<<“Size of int: “<< sizeof(int);
cout<<“Size of float: "<< sizeof(float);
cout<<“Size of double: \n”<< sizeof(double);
cout<<“Size of pointer: \n”<< sizeof(void *);
return 0;}
output:
16
Lecture Five - Expressions & Operators in C++ C++ Programming Language
Size of char: 1 bytes
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of pointer: 8 bytes

 Address of operator [&]


The address of (&) operator is said to be overloaded operator because it can be used for more than
one operations. When applied on binary operands, it is interpreted by the compiler as a bitwise &
(AND) operator. But when the symbol is followed by a variable as shown in the following statement,
it returns memory address allocated to the variable:
int location = &distance;
The statement assigns memory address of distance to location which can be formatted and displayed
in hexadecimal format as follows:
cout<<setbase(16)<<location;

 Cast ( ) operator
Type casting operator represented with brackets () converts (casts) a value from one data type to
another. This is achieved by preceding the expression to be converted by the new type enclosed
between parentheses (()) or using functional notation. For example, if distance is a float, it can be
casted to an integer as follows:
float distance = 3.14;
approx_dist = (int)distance; //C-type casting
approx_dist = int(distance); //functional notation

In C++, casting a variable declared as double or float to int results in loss of precision due to loss in
floating-point part. In the above example, the value assigned to approx_distance is 3!

 Comma [ , ] operator
The comma (,) operator separates two or more expressions where only one expression is expected.
The result of the comma-separated list is the value of the last expression. For example, the following
expression assigns 3 to b first, then assigns b+2 to a, so that a becomes 5 and b holds 3:
a = (b=3, b+2);

 Scope resolution [::] operator

The scope resolution operator represented by two consecutive colons is used to identify and
disambiguate similar identifiers used in different scopes. The operator is used to identify a member of
a namespace or class. For example, if using namespace declaration is omitted in a C++ program, you
can use:: to access cout as follows:
std::cout<<“I Enjoy Programming!\n”;

Operator Precedence
17
Lecture Five - Expressions & Operators in C++ C++ Programming Language

C++ uses precedence rule to evaluate arithmetic expressions: The precedence rule from the highest to
the lowest is as follows:

Exercises
Exercise 1

 What values do the following arithmetic expressions have?

3/10
11%4
15/2.0
3+4%5
3*7%4
7%4*3

Exercise 2
18
Lecture Five - Expressions & Operators in C++ C++ Programming Language

a) How are operands and operators in the following expression associated?


x = –4 * i++ – 6 % 4;
Insert parentheses to form equivalent expressions.
b) What value will be assigned in part a to the variable x if the variable i has a value of –2?

Exercise 3
The int variable x contains the number 7. Calculate the value of the following logical expressions:

a) x < 10 && x >= –1


b) !x && x >= 3
c) x++ == 8 || x == 7

Exercise 4

What screen output does the following program?


// Evaluating operands in logical expressions.
#include <iostream>
using namespace std;
int main()
{ cout << boolalpha; // Outputs boolean values
// as true or false
bool res = false;
int y = 5;
res = 7 || (y = 0);
cout << "Result of (7 || (y = 0)): " << res
<< endl;
cout << "Value of y: " << y << endl;
int a, b, c;
a = b = c = 0;
res = ++a || ++b && ++c;
cout << '\n‘ << " res = " << res << ", a = " << a
<< ", b = " << b << ", c = " << c << endl;
a = b = c = 0;
res = ++a && ++b || ++c;
cout << " res = " << res
<< ", a = " << a
<< ", b = " << b
<< ", c = " << c << endl;
return 0;
}
Solution (1)
a. 0 b. 3 c. 7.5 d. 7 e. 1 f. 9

Solution (2)
19
Lecture Five - Expressions & Operators in C++ C++ Programming Language

a. x = ( ((–4) * (i++)) – (6 % 4) )
b. The value 6 will be assigned to the variable x.

Solution (3)
a. True b. false c. false

Solution (4)
Result of (7 || (y = 0)): true Value of y: 5
res = true, a = 1, b = 0, c = 0
res = true, a = 1, b = 1, c = 0

Homework (Expressions & Operators in C++)


1. What is the exact output of the program below? Indicate a blank space in the output by writing
the symbol ! . Indicate a blank line in the output by writing blank line.
#include <iostream>
using namespace std;
int main(){
int n = 4, k = 2;
cout << ++n << endl;
cout << n << endl;
cout << n++ << endl;
cout << n << endl;
cout << -n << endl;
cout << n << endl;
cout << --n << endl;
cout << n << endl;
cout << n-- << endl;
cout << n << endl;
cout << n + k << endl;
cout << n << endl;
cout << k << endl;
cout << n << k << endl;
cout << n << endl;
cout << " " << n << endl;
cout << " n" << endl;
cout << "\n" << endl;
cout << " n * n = "; //CAREFUL!
cout << n * n << endl;
cout << 'n' << endl;
return 0;}
2. What is the output of the program below?
#include <iostream>
using namespace std;
int main(){
int n = 3;
while (n >= 0) {
cout << n * n << endl;
--n; }
20
Lecture Five - Expressions & Operators in C++ C++ Programming Language
cout << n << endl;
while (n < 4)
cout << ++n << endl;
cout << n << endl;
while (n >= 0)
cout << (n /= 2) << endl;
return 0;}
3. What is the output of the program below?
#include <iostream>
using namespace std;
int main(){
int n;
cout << (n = 4) << endl;
cout << (n == 4) << endl;
cout << (n > 3) << endl;
cout << (n < 4) << endl;
cout << (n = 0) << endl;
cout << (n == 0) << endl;
cout << (n > 0) << endl;
cout << (n && 4) << endl;
cout << (n || 4) << endl;
cout << (!n) << endl;
return 0;}
4. What is the output of the following program?
#include <iostream>
using namespace std;
int main(){
enum color_type {red, orange, yellow, green, blue, violet};
color_type shirt, pants;
shirt = red;
pants = blue;
cout << shirt << " " << pants << endl;
return 0;}
5. What is the output when the following code fragment is executed?
int i = 5, j = 6, k = 7, n = 3;
cout << i + j * k - k % n << endl;
cout << i / n << endl;

6. Given the following operation, what will be the value of the variable q?

int q;
int j = 36;
int m = 6;
q = j % m;

 What is the output when the following code fragment is executed?

#include <iostream>
using namespace std;
int main(){
21
Lecture Five - Expressions & Operators in C++ C++ Programming Language
cout << "\n\n Print the result of some specific operation :\n";
cout << "--------------------------------------------------\n";
cout << " Result of 1st expression is : "<< (-1+4*6) <<"\n" ; //-1 + 24
= 23
cout << " Result of 2nd expression is : "<< ((35+5)%7) <<"\n" ; //40
% 7 = 5 (remainder of 40/7)
cout << " Result of 3rd expression is : "<< (14+-4*6/11) <<"\n" ;
//14 - (24/11)= 14 - 2 = 12
cout << " Result of 4th expression is : "<< (2+15/6*1-7%2) <<"\n\n"
; //2 + (15/6) - remainder of (7/2) = 2 + 2 - 1 = 4 - 1 = 3 }

 What is the output when the following code fragment is executed?

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
cout << "\n\n Formatting the output using type casting:\n";
cout << "----------------------------------------------\n";
cout<<"Print floating-point number in fixed format with 1 decimal
place: ";
cout << fixed << setprecision(1);
cout<<"\nTest explicit type casting :\n";
int i1 = 4, i2 = 8;
cout << i1 / i2 << endl;
cout << (double)i1 / i2 << endl;
cout << i1 / (double)i2 << endl;
cout << (double)(i1 / i2) << endl;
double d1 = 5.5, d2 = 6.6;
cout<<"\nTest implicit type casting :\n" ;
cout << (int)d1 / i2 << endl;
cout << (int)(d1 / i2) << endl;
cout <<"\nint implicitly casts to double: \n";
d1 = i1;
cout << d1 << endl; // 4.0
cout<<"double truncates to int!: \n";
i2 = d2;
cout << i2 << endl; // 6 }

 Write a C++ program to display the current date and time.


Sample Output:
Display the Current Date and Time :
----------------------------------------
seconds = 57
minutes = 33
hours = 12
day of month = 6
month of year = 7
year = 2017
weekday = 4
22
Lecture Five - Expressions & Operators in C++ C++ Programming Language
day of year = 186
daylight savings = 0
Current Date: 6/7/2017
Current Time: 12:33:57

 Write a program in C++ that converts kilometers per hour to miles per hour.
Sample Output:
Convert kilometers
per hour to miles per hour :
----------------------------------------------------
Input the distance in kilometer : 25
The 25 Km./hr. means 15.5343 Miles/hr.

 Write a program in C++ to convert temperature in Fahrenheit to Celsius.


Sample Output:
Convert temperature in Fahrenheit to Celsius :
---------------------------------------------------
Input the temperature in
Fahrenheit : 95
The temperature in Fahrenheit : 95
The temperature in Celsius : 35

 Write a program in C++ to find the area and circumference of a circle.


Sample Output:
Find the area and circumference of any circle :
----------------------------------------------------
Input the radius(1/2 of diameter) of a circle : 5
The area of the circle is : 78.5397
The circumference of the circle is : 31.4159

 Write a program in C++ to find the Area and Perimeter of a Rectangle.


Sample Output:
Find the Area and Perimeter of a Rectangle :
-------------------------------------------------
Input the length of the rectangle : 10
Input the width of the rectangle : 15
The area of the rectangle is : 150
The perimeter of the rectangle is : 50

 Write a program in C++ to swap two numbers.


Sample Output:
Swap two numbers :
-----------------------
Input 1st number : 25
Input 2nd number : 39
After swapping the 1st number is : 39
After swapping the 2nd number is : 25

 Write a program in C++ to print the sum of two numbers using variables.
Sample Output:
Print the sum of two numbers:
23
Lecture Five - Expressions & Operators in C++ C++ Programming Language
-----------------------------------
The sum of 29 and 30 is: 59

 To what do the following expressions evaluate?


a. 17/3
b. 17%3
c. 1/2
d. 1/2*(x+y)

 Given the declarations:


float x;
int k, i = 5, j = 2;

To what would the variables x and k be set as a result of the


assignments
a. k = i/j;
b. x = i/j;
c. k = i%j;
d. x = 5.0/j;

24

You might also like