Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Arithmetic expression

Definition
• Expression is the combination of the
constants, variables, and operators arranged
according to the syntax of C++ language.

• Examples:
int x =10; float y = 2.5;
cout<< x+y / 5;
• Expression consists of
– Operand such as variable, constant
– Operator such as + - * / > <
• Types of operators based on the number of
operands:
– unary: negative such as -7 , !x , sizeof(x), ++x --x
– Binary: minus 2-1 x*y a/2 100%3
– Ternary: condition? Value1 : value2 ;
Arithmetic Operators
• C++ provides the following arithmetic operations:
+ (addition)
binary - (subtraction)
unary - (negative sign)
* (multiplication)
/ (division)
% (remainder) mod
• The % operator applies only to integer values
Cout<< 5%2; // it prints 1
Cout<< 4%2; // 0
Cout<< 9%3 ; // 0
Cout<<9%2; // 1
Cout<< 10%3; // 1
Cout<<19% 4 ; // 3
Cout<< 6/3 ; // 2
Cout<< 9/2; // 4
Cout<< 9.0 / 4.0 ; // 4.5
Cout<<39 /10 ; // 3.9 - it prints 3
Cout<<39 %10 ; // 9
Cout<<2154678 / 10 ; // 215467
Cout<<2154678%10 ; // 8
Cout<<123/100; // 1.23 it prints 1
Cout<<123%100; // it prints 23
Cout<< 300 % 1000 ; //300
Cout<< 300 / 1000 ; // 0
Cout<<(x+y+z) / 3;
Cout << 2.5 % 3 ; // error
% is used only for integers
Priorities
• Priorities between arithmetic operations:
1. parenthesized expressions
2. unary operators negative ! ++ --
3. / * %
4. + binary –
5. Assign operator =
• Operators with an equal priority are
performed left to right.
Example
1+2*-4-8+6/2%(2+4)
1+(2*(-4))-8+6/2%6
1 + (-8) – 8 +(6/2)%6
1+(-8) -8 + 3 % 6
1 + (-8) -8 + 3
-7 – 8 + 3
-15 + 3
-12
Arithmetic Expressions
• Expressions can contain arithmetic operators,
numeric values, variables, character values

• Character values as operands for arithmetic


operators are replaced by their ascii values.
Examples
‘a’*2=194
2-’A’=-63
1+’1’=50
0-’0’= -48
Example: Write a program to read 3 integer values and print their
average. For example,
Input 3 integers:10 20 30
average= 20

#include<iostream>
using namespace std;
int main()
{ int x,y,z;
cout<<“Input 3 integers:”;
cin>>x>>y>>z;
cout<<“average=”<<(x+y+z)/3.0;
cout<<endl;
}
Example: Write a program to read compute the area of a rectangle. For
example,
Input rectangle length:1.2
input rectangle height: 10.2
area= 14.4

#include<iostream>
using namespace std;
int main(){
double L,H;
cout<<“Input rectangle length:”;
cin>>L;
cout<<“Input rectangle height:”;
cin>>H;
cout<<“area=”<<L*H;
cout<<endl;
}
Example: Write a program to convert from fahrenhiet to celsius. For
example,
Input fahrenhiet temperature:32
The celsius equivalent is: 0

#include<iostream>
using namespace std;
int main(){
double f;
cout<<“Input fahrenhiet temperature:”;
cin>>f;
cout<<“The celsius equivalent is:”<<(5/9)*(32-f);
cout<<endl;
}
Type casting
• Type casting refers to the conversion of one data
type to another in a program.

• Typecasting can be done in two ways:


1. Implicit type casting (automatically by the compiler )
2. Explicit type casting(manually by the programmer or
user)

• Type Casting is also known as Type Conversion.


1. Implicit type casting
cout << 5 / 2.0; // int / double = double
cout << endl;
cout << 5.0 / 2.0; // double / double = double
cout << endl;
cout << 5.0 / 3; // double / int = double
cout << endl;
cout << 'a' + 2;// char + int = int
cout << endl;
cout << 'a' + 'b'; // char + char = int
Mixed Operands
• Mixed operands are operands of different data types and are evaluated as
follows

Operator
(+ - * /) char int float double

char int int float double

int int int float double

float float float float double

double double double double double

• The % operator can be used only with integers.


Examples
cout<<‘b’-’b’; //prints 0
cout<<‘b’+1;// prints 99
cout<<‘A’+1.5; //prints 66.5
cout<<2/3; // prints 0
cout<<2/3.0; //prints 0.666667
cout<<2.0/3.0; //prints 0.666667
cout<<4.0/2.0; //prints 2
2. Explicit type casting
• Casting is an operation that allows us to
change the type of a variable.

• Two ways of explicit casting in C++:


– The traditional way of casting (C++ functional cast).
– C++’s newer casting operators.
C++ functional cast
The general form to cast the value of the expression to type
T is as follows:
T(exp)
Examples:
cout<<int (‘a’)/2; // prints 48
cout<<char( 97); // prints a
cout<<float (5); // prints 5
cout<<int(8.2); //prints 8
cout<<float (8)/3;//prints 2.666667
cout<<float(8/3);//prints 2
cout<<char(97.987); //a
float x=2.51;
cout<<double(x);//prints 2.51
Explicit Cast operators
• An explicit cast operator is a unary operator which forces
one data type to be converted into another data type.
• Casting operations can vary from harmless to dangerous1.
• C++ provides a number of casting operators that make the
safety2 of the cast much more explicit.
• static_cast
• dynamic_cast
• const_cast
• reinterpret_cast

 We discuss only the static_cast here and consider the


others as the need arises
static_cast
• The most common use is for conversions
between numeric types.
• It is possible to request the conversion
between different basic data types:

char int float double

• Its syntax is given below:


static_cast<desired type> (expression);
Example on static_cast

#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
int a = f; // this is how you do in C
int b = static_cast<int>(f);
cout << b;
}
Operators in C++
• Operators in C++ can be classified into 6
types:
1. Arithmetic Operators. + * / - %
2. Assignment Operators. = += -= /= %= *=
3. Relational Operators. < <= > >= == !=
4. Logical Operators. && || !
5. Bitwise Operators. & | ^ >> << ~
6. Other Operators.
Arithmetic operators

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Modulo Operation
% (Remainder after
division)
Bitwise Operators
In C++, bitwise operators perform operations on integer data at the individual
bit-level. These operations include testing, setting, or shifting the actual bits.

Operator Description
& Binary AND
| Binary OR
^ Binary XOR
Binary One's
~
Complement
<< Binary Shift Left
>> Binary Shift Right

Note: Bitwise operators can only be used alongside char and int data types.
C++ Bitwise AND Operator
The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it
returns 0.
The following table demonstrates the working of the bitwise AND operator.
Let a and b be two operands that can only take binary values i.e. 1 and 0.

a b a&b
0 0 0
0 1 0
1 0 0
1 1 1
Example
#include <iostream>
using namespace std;
int main() {
// declare variables
int a = 12, b = 25;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a & b = " << (a & b) << endl;
return 0;
}

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)
/Bitwise AND Operation of 12 and 25

00001100
& 00011001
----------------------
00001000 = 8 (In decimal)
Relational Operators
Operator Meaning Example

3 == 5 gives
== Is Equal To
us false

3 != 5 gives us
!= Not Equal To
true

3 > 5 gives us
> Greater Than
false

3 < 5 gives us
< Less Than
true

Greater Than 3 >= 5 give us


>=
or Equal To false

Less Than or 3 <= 5 gives


<=
Equal To us true
Relational Operaters
• Relational operators are
< <= > >= == !=
• Relational operators return either 0 (false) or 1 (true)
• == != operators have less precedence than < <= > >=
• Relational operators have lower precedence than
arithmetic operators
• Relational operators with equal priority evalute from left
to right
• There might be differences between compilers
(1>2>=3) = 0 in Visual C++
(1>2>=3) is ambigous in Borland C++
(1>2>3) = 0 in both Visual and Borland C++
Examples
cout<< (‘a’==’b’); // prints 0
cout<<(‘b’==’b’); // prints 1
cout<<(‘b’<’h’); // prints 1
cout<<(8!=4); // prints 1
cout<<(4>=4);// prints 1
cout<<(4<4);// prints 0
cout<<(1+2>=5!=6); //prints 1
cout<<(1*2>3%4<=6!=8>2==0); //prints 1
Logical Operators
• Logical operators are
&& (and)
|| (or)
! (negation)
• Logical operators return 0 (false) or 1 (true)

a b a&&b a||b !a

0 0 0 0 1

0 nonzero 0 1 1

nonzero 0 0 1 0

nonzero nonzero 1 1 0
Logical Operators Cont.
• && has higher precedence than ||
• && || have less precedence than any
relational operator
• ! has higher precedence than any
arithmetic operator
• Multiple || are performed from left to right
• Multiple && are performed from left to right
Example
cout<<8||2; // prints 1
cout<<-8&&2000; // prints 1
cout<<70||0; // prints 1
cout<<-5&&0; // prints 0
cout<<!100; // prints 0
cout<<!100&&100; // prints 0
cout<<0&&!0; // prints 0
int x=100;
cout<<(x>=0 && x<=200); // prints 1
cout<<!(x>=500); // prints 1
cout<<(!x>=500); // prints 0
cout<<!x||x&&x-x; // prints 0
Example
4>3*6+7%2-1>=15==3&&1!=7||5&&9||1+2 =
4>18+7%2-1>=15==3&&1!=7||5&&9||1+2 =
4>18+1-1>=15==3&&1!=7||5&&9||1+2 =
4>19-1>=15==3&&1!=7||5&&9||1+2 =
4>18>=15==3&&1!=7||5&&9||1+2 =
4>18>=15==3&&1!=7||5&&9||3 =
0>=15==3&&1!=7||5&&9||3 =
0==3&&1!=7||5&&9||3 =
0&&1!=7||5&&9||3 =
0&&1||5&&9||3 =
0||5&&9||3 =
0||1||3 =
1||3 =
1
Other operators
Operator Description Example
returns the
sizeof size of data sizeof(int); // 4
type

string result =
returns value
(5 > 0) ?
?: based on the
"even" :
condition
"odd"; // "even"

represents
&num; //
memory
& address of
address of the
num
operand

accesses
members of
. struct s1.marks = 92;
variables or
class objects

used with
pointers to
ptr->marks =
-> access the
92;
class or struct
variables

prints the
<< cout << 5;
output value

gets the input


>> cin >> num;
value
Math Library
Complex arithmetic operations can be accomplished by calling math
library functions. In this case, use #include <math.h> directive.

Examples of math functions:


sqrt(x) exp(x)=ex
log(x)// base e log10(x)
fabs(x) fabs(x)
ceil(x) floor(x) round(x)
pow(x,y) fmod(x,y)
sin(x) cos(x) tan(x)
x, y are of type double and the results returned by these functions are
of type double.
floor function
Positive numbers
cout << floor(2.999);// 2
cout << floor(2.333); // 2
Negative numbers
cout << floor(-2.999);// -3
cout << floor(-2.333); // -3
round vs ceil
• ceil( ) differs from Math. round( ) in that it
always rounds up, rather than rounding
up or down to the closest integer. Also,
note that Math. ceil( ) does not round
negative numbers to larger negative
numbers; it rounds them up toward zero.
ceil

Positive numbers
cout << ceil(2.999);// 3
cout << ceil(2.333); // 3

Negative numbers
cout << ceil(-2.999);// -2
cout << ceil(-2.333); // -2
round
Positive numbers
cout << round(2.999);// 3
cout << round(2.0001); // 2
Negative numbers
cout << round(-2.999);// -3
cout << endl;
cout << round(-2.333); // -2
Examples
The math expression
a2 - |b|
is written in C as
pow(a,2)-fabs(b)
or as
a*a-fabs(b)
Examples
The math expression
a+sin(b2)+cos2(c)
ab - 1
log10(ab)
is written in C as
(a+sin(b*b)+pow(cos(c),2))/(a*b-1/log10(a*b))
Example: write a program to read 2 real values of x and y
and print the value of the expression:
x2 – y3
cos(x+y)

#include<iostream>
using namespace std;
int main()
{ int x,y;
cout<<“Input values of x and y:”;
cin>>x>>y;
cout<<“The value of the expression=“;
cout<<(x*x-pow(y,3))/cos(x+y);
}
Rand() function
rand() function is an inbuilt function in C++ STL, which is defined in header
file <cstdlib>. rand() is used to generate a series of random numbers.

// C++ program to demonstrate the use of rand()


#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
// This program will create same sequence of
// random numbers on every program run
for (int i = 0; i < 5; i++)
cout << rand() << " ";

return 0;
}

You might also like