0% found this document useful (0 votes)
64 views

Selection Structures C++

This document discusses expressions and arithmetic in C++. It explains that expressions can combine literal values and variables using operators. It provides an example program that adds two integers entered by the user. It also discusses unary, binary, and ternary operators. The document explains different arithmetic operators like addition, subtraction, multiplication, division, remainder, and their precedence rules. It covers type casting, overflow, underflow, and examples of increment/decrement operators. Finally, it discusses logical, bitwise, and relational operators.

Uploaded by

Hassan Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Selection Structures C++

This document discusses expressions and arithmetic in C++. It explains that expressions can combine literal values and variables using operators. It provides an example program that adds two integers entered by the user. It also discusses unary, binary, and ternary operators. The document explains different arithmetic operators like addition, subtraction, multiplication, division, remainder, and their precedence rules. It covers type casting, overflow, underflow, and examples of increment/decrement operators. Finally, it discusses logical, bitwise, and relational operators.

Uploaded by

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

Expressions and

Arithmetic
Lecture 4
Maemoona Kayani
Expressions
• A literal value like 34 and a properly declared variable like x are examples of simple expressions. We can use
operators to combine values and variables and form more complex expressions.
• Example shows how the addition operator (+) is used to add two integers.
#include <iostream>
int main() {
int value1, value2, sum;
std::cout << "Please enter two integer values: ";
std::cin >> value1 >> value2;
sum = value1 + value2;
std::cout << value1 << " + " << value2 << " = " << sum << '\n';
}
Expressions contd.
• int value1, value2, sum;
This statement declares three integer variables, but it does not initialize them. As we examine the rest of the
program, we will see that it would be superfluous to assign values to the variables here.
• std::cout << "Please enter two integer values: ";
This statement prompts the user to enter some information. This statement is our usual print statement, but it is not
terminated with the end-of-line marker '\n'. This is because we want the cursor to remain at the end of the printed
line so when the user types in values they appear on the same line as the message prompting for the values. When
the user presses the enter key to complete the input, the cursor will automatically move down to the next line.
• std::cin >> value1 >> value2;
This statement causes the program’s execution to stop until the user types two numbers on the keyboard and then
presses enter. The first number entered will be assigned to value1, and the second number entered will be assigned
to value2. Once the user presses the enter key, the value entered is assigned to the variable. The user may choose
to type one number, press enter, type the second number, and press enter again. Instead, the user may enter both
numbers separated by one of more spaces and then press enter only once. The program will not proceed until the
user enters two numbers.
Expressions contd.

• sum = value1 + value2;


This is an assignment
statement because it
contains the assignment
operator (=).
Operators
• Used for performing numeric calculations

• C++ has unary, binary, and ternary operators


• unary(1 operand)-5
• binary(2 operands) 13 -7
• ternary(3 operands) exp1 ?exp2 :exp3
Binary Arithmetic Operator

Remainder operator is also known as modulus operator


Integer and Real Division
• int result = 5/2; //  result equal to2
• float result=5.0/2; //  result equal to 2.5
If any of the operand is a real value (float or double) the
division will be performed as “Real Division”
Remainder/Modulus Operator
•Operands of modulus operator must be integers
34 %5 (valid, result 4)
-34 %5(valid, result -4)
34 %-5(valid, result 4)
-34 %-5(valid, result -4)

NOTE: 34 % 1.2 is an Error


Arithmetic Expressions
• Convert the following expression into C++ code
Example: Converting Temperature
• Write a program that converts a Fahrenheit to Celsius
using the formula:
Multiple Assignment
• The assignment operator (=) can be used more than 1 time in an expression
x = y = z = 5;
• Associates right to left
x = (y = (z = 5));
Combined Assignment
•Also consider it “arithmetic” assignment
•Updates a variable by applying an arithmetic operation to a
variable
•Operators: += -= *= /= %=
•Example:
sum += amt; is short for sum = sum + amt;
p += 3 + y; means p = p+(3+y);
More Examples
• x += 5; means x = x + 5;
• x -= 5; means x = x –5;
• x *= 5; means x = x * 5;
• x /= 5; means x = x / 5;
• x %= 5; means x = x % 5;
• RULE: The right hand side is evaluated first, then the combined
assignment operation is done.
• x *= a + b; means x = x * (a + b);
• 3-
Increment and Decrement Operators
Increment and Decrement Operators
Evaluate the followings:
int val= 10;
int result = 10 * val++;
cout<<val<<“ “<<result;

int val= 10;


int result = 10 * ++val;
cout<<val<<“ “<<result;
Increment and Decrement Operators
Output of the following code:
int x = 5, y = 5, z;
x = ++x;
y = --y;
z = x++ + y--;
cout<< z;
Increment and Decrement Operators
Output of the following code:
int num1 = 5;
int num2 = 3;
int num3 = 2;
num1 = num2++;
num2 = --num3;
cout << num1 << num2 << num3 <<endl;
Examples
int a=1;
int b;
b = ++a * ++a;
cout<<a: "<<a<<", b: "<<b; cout<<endl;

a=1; b = a++ * a++;


cout<<"a: "<<a<<", b: "<<b; cout<<endl;

a=1; b = ++a * a++;


cout<<"a: "<<a<<", b: "<<b; cout<<endl;

a=1; b = a++ * ++a;


cout<<"a: "<<a<<", b: "<<b; cout<<endl;
Examples
Type Casting
Type Coercion
Coercion: automatic conversion of an operand to another data type
•Promotion: converts to a higher type
float p; p = 7; 7 (int) converted to float 7.0
•Demotion: converts to a lower type
Int q; q = 3.5; 3.5 (float) converted to int 3
Coercion Rules
1) char, short, unsigned short are automatically promoted to
int
2) When operating on values of different data types, the
lower one is promoted to the type of the higher one.
3) For the assignment operator = the type of expression on
right will be converted to the type of variable on left.
3-
Implicit Type Casting
A mechanism by which we can change the data type of
a variable (no matter how it was originally defined)
•Two ways:
1.Implicit type casting(done by compiler)
2.Explicit type casting(done by programmer)
Implicit Type Casting
•As seen in previous examples:
void main( )
{
char c = 'a';
float f = 5.0;
float d = c + f;
cout<<d<<“ “<<sizeof(d)<<endl;
cout<<sizeof(c+f);
}
Numeric Type Conversion
Consider the following statements:
short i=10;
long k=i*3+4;
doubled=i*3.1+k/2;
cout<<d;
Type Conversion Rules
Auto Conversion of Types in C++
1. If one of the operands is long double, the other is converted into long double
2. Otherwise, if one of the operands is double, the other is converted into
double.
3. Otherwise, if one of the operands is unsigned long, the other is converted
into unsigned long.
4. Otherwise, if one of the operands is long, the other is converted long.
5. Otherwise, if one of the operands is unsigned int, the other is converted into
unsigned int.
6. Otherwise, both operands are converted into int.
Implicit Type
Conversion in C+
+
Overflow and Underflow
When a variable is assigned a value that is too large or too
small in range:
–Overflow
–Underflow
–After overflows/underflow values wrap around the
maximum or minimum value of the type
Example
// testVar is initialized with the maximum value for a short.
short int testVar= 32767;
// Display testVar.
cout<<"\n Orignalvalue: "<<testVar<<endl;
// Add 1 to testVar to make it overflow.
testVar= testVar+ 1;
cout<<"\n ValueOverflow +1: "<<testVar<< endl;
// Subtract 1 from testVar to make it underflow.
testVar= testVar-1;
cout<<"\n Valueunderflow -1: "<<testVar<< endl;
Explicit Type Casting
Explicit casting performed by programmer. It is performed by using cast
operator
float a=5.0, b=2.1;
int c = a%b; // ERROR
•Three Styles

int c = (int)a % (int)b; //C-style cast


int c = int(a)% int(b); // Functional notation
int c = static_cast<int>(a) % static_cast<int>(b);
cout<<c;
Explicit Type Casting
-Casting does not change the variable being cast.
For example, d is not changed after casting in the following
code:
doubled = 4.5;
int j = (int) d; //C-type casting
int i= static_cast<int>(d); // d is not changed
cout<<j<<“ “<<d;
Explicit Type Casting Example
Casting between char and Numeric Types
• int i= 'a';// Same as inti= (int) 'a’;
• char c = 97;// Same as char c = (char)97;
Using ++, --on “char” type
-The increment and decrement operators can also be
applied on char type variables:
Example:
char ch= 'a’;
cout<< ++ch;
Int to String conversion
-C++ style:
#include<sstream>
void main() {
int val=0;
stringstream ss;
cout<<“Enter Value: “; cin>>val;
ss<< val; //Using stream insertion op.
string str_val= ss.str();
cout<<“\n Output string is: “<<str_val;
}
Equality and Relational Operators
Logical Operators
• Logical operators are useful when we want to test multiple conditions

•Three types:
1. boolean AND
2. boolean OR
3. boolean NOT
Boolean AND or Logical AND
• Symbol: &&
•All the conditions must be true for the whole expression to
be true
–Example:
if ( (a == 10)&&(b == 10)&&(d == 10) )
cout<<“a, b, and d are all equel to 10”;
Boolean OR/Logical OR
•Symbol: ||
•ANY condition is sufficient to be true for the whole expression to be
true
–Example:
if (a == 10|| b == 9||d == 1)
// do something
Boolean NOT/Logical NOT
•Symbol: !
•Reverses the meaning of the condition (makes a true condition false,
OR a false condition true)
–Example:
if ( ! (marks > 90))
// do something
Bitwise Operators (integers)
• Bitwise "and" operator &
• Bitwise "or" operator |
• Bitwise "exclusive or" operator ^
–(0 on same bits, 1 on different bits)
• Bitwise "ones complement" operator ~
• Shift left <<
• Shift right >>
Bitwise Operators (Example)
Mathematical Expressions
•An expression can be a constant, a variable, or a combination of
constants and variables combined with operators
•Can create complex expressions using multiple mathematical
operators:
•2
• height
•a + b / c
Using Mathematical Expressions
Precedence Rules
Order of Operations
Associativity of Operators
•*/%+- all associate left to right
3 + 2 + 4 + 1 = (3 + 2) + 4 + 1 = ((3+2)+4)+1 =(((3+2)+4)+ 1)
•parentheses() can be used to override the order of operations

2 + 2 * 2 –2 = 4
(2 + 2) * 2 –2 = 6
2 + 2 * (2 –2) = 2
(2 + 2) * (2 –2) = 0
• 3
Algebraic Expressions

• Multiplication requires an operator


Area = lw is written as Area = l * w;
• There is no exponentiation operator

Area = s2 is written as Area = pow(s, 2);


(note: pow requires the cmath header file) OR
Area = s*s;
• Parentheses may be needed to maintain order of operations
Precedence
Rules –
Example 1
Precedence
Rules –
Example 2
Precedence Rule – Example 3
Precedence Rules (Overriding)
•For example: x = 3 * a -++b % 3;

•If we intend to have the statement evaluated


differently from the way specified by the precedence
rules, we need to specify it using parentheses ( )
•Using parenthesis:
x = 3 * ((a -++b)%3);
Any Questions

You might also like