You are on page 1of 41

Computer Programming (CSI101)

Expressions

Prof. Pranay Kumar Saha


Assistant Professor
Department of Computer Sc. and Engineering
Expression
Variables and constants linked with operators
• Arithmetic expressions
⚫ Uses arithmetic operators

⚫ Can evaluate to any value

• Assignment expression
⚫ Uses assignment operators

⚫ Evaluates to value depending on assignment

• Logical expressions
⚫ Uses relational and logical operators

⚫ Evaluates to 1 or 0 (true or false) only


Arithmetic Operators
Binary operators distance = rate * time ;

Addition: + netIncome = income - tax ;


Subtraction: – speed = distance / time ;
Division: /
area = PI * radius * radius;
Multiplication: *
y = a * x * x + b*x + c;
Modulus: %
Unary operators quotient = dividend / divisor;

Plus: + remain =dividend % divisor;


Minus: –
% can be used only with integer operands
Arithmetic Operators

• In decreasing order of priority


1.Parentheses :: ( )
2.Unary minus :: –5
3.Multiplication, Division, and Modulus
4.Addition and Subtraction

• For operators of the same priority, evaluation is from left to


right as they appear
• Parenthesis may be used to change the precedence of
operator evaluation
Examples:Arithmetic Expressions

• a + b * c –d / e a + (b * c) – (d / e)
• a * –b + d % e –f a * (– b) + (d % e) – f
• a –b + c + d (((a – b) + c) + d)
• x*y*z ((x * y) * z)
• a+b+c*d*e (a + b) + ((c * d) * e)
Type of Values

Integer Arithmetic
⚫ If all operands of an operator are integer (int variables or integer

constants), the value is always integer


⚫ When the operands in an arithmetic expression are integers, the


expression is called integer expression and the operation is called integer
arithmetic
Type of Values

Real Arithmetic
Arithmetic operations involving only real or floating-point operands.
• Since floating-point values are rounded to the number of significant digits
permissible, the final value is an approximation of the final result.

1.0 / 3.0 * 3.0 will have the value 0.99999 and not 1.0

• The modulus operator cannot be used with real operands.

Mixed Arithmetic
⚫ If at least one operand is real, the value is real
Assignment Expression
⚫ Uses the assignment operator (=)
⚫ General syntax:
⚫ variable_name = expression

⚫ variable_name1=varable_name2

⚫ Left of = is called l-value, must be a modifiable variable


⚫ Right of = is called r-value, can be any expression
⚫ Data types of RHS must be compatible with LHS
⚫ Examples:
⚫ velocity = 20

⚫ b = 15; temp = 12.5

⚫ A = A + 10

⚫ v = u + f * t

⚫ s = u * t + 0.5 * f * t * t
Assignment Expression
⚫ Several variables can be assigned the same value using multiple
assignment operators
⚫ a = b = c = 5;

⚫ flag1 = flag2 = ‘y’;

⚫ speed = flow = 0.0;

⚫ Easy to understand if you remember that the assignment expression has

a value
⚫ Multiple assignment operators are right-to-left associative;
Types of l-value and r-value
⚫ Usually should be the same
⚫ If not, the type of the r-value will be internally converted to the type of the l-value, and then
assigned to it
⚫ Example1:
⚫ double a;
⚫ a = 2*3;
⚫ Type of r-value is int and the value is 6
⚫ Type of l-value is double, so stores 6.0
⚫ Example2
⚫ int a;
⚫ a = 2*3.2;
⚫ Type of r-value is float/double and the value is 6.4
⚫ Type of l-value is int, so internally converted to 6
⚫ So a stores 6, not the correct result
More on Assignment
⚫+=, -=, *=, /=, %=
⚫ Operators for special type of assignments

⚫ a += b is the same as a = a + b

⚫ Same for -=, *=, /=, and %=

⚫ Exact same rules apply for multiple assignment operators


More on Assignment
⚫ +=, -=, *=, /=, %=
⚫ Operators for special type of assignments
⚫ a += b is the same as a = a + b
⚫ Same for -=, *=, /=, and %=
⚫ Exact same rules apply for multiple assignment operators
⚫ Examples:-
⚫ Two variables x=5, y=10
⚫ x+=y, x=?

⚫ x-=y, x=?

⚫ x*=y, x=?

⚫ x/=y, x=?

⚫ X % y, x=?
Problem Solution: Typecasting
⚫ Changing the type of a variable
int a=10, b=4, c;
during its use
float x;
c = a / b; ⚫ General form
x = a / b; ⚫ (type_name) variable_name
The value of c will be 2
The value of x will be 2.0
⚫ Example
But we want 2.5 to be stored in x ⚫ x = ((float) a)/ b;

⚫ Now x will store 2.5 (type of a is


considered to be float for this
operation only, now it is a mixed-
⚫ mode expression, so real values are
generated)
Restrictions on typecasting
⚫ Not everything can be typecast to anything

⚫ float/double should not be typecast to int (as an int


cannot store everything a float/double can store)

⚫ int should not be typecast to char (same reason)


• General rule: make sure the final type can store any
value of the initial type
Which code is correct?
int a, b; int a, b; int a, b;
float avg; float avg; float avg;
scanf(“%d%d”, &a, &b); scanf(“%d%d”, &a, &b); scanf(“%d%d”, &a, &b);
avg = (a + b)/2; avg = (float) (a + b))/2; avg = (a + b)/2.0;
printf(“%f\n”, avg); printf(“%f\n”, avg); printf(“%f\n”, avg);

Finding Average of two numbers?


Logical Expression
⚫ Uses relational and logical operators

⚫ Informally, specifies a condition which can be true or false

⚫ Evaluates to value 0 or 1

⚫ 0 implies the condition is false

⚫ 1 implies the condition is true


Logical Operator
⚫ There are two logical operators in C (also
called logical connectives). X Y X && Y X || Y
⚫ && ➔ Logical AND
False (0) False (0) False (0) False (0)
⚫ Result is true if both the operands are true.
False(0) True(non False (0) True(non
⚫ | | ➔ Logical OR
zero) zero)
⚫ Result is true if at least one of the True(non False (0) False (0) True(non
zero) zero)
⚫ They act upon operands that are themselves
logical expressions. True (on True(non True(non True(non
zero) zero) zero) zero)
⚫ The individual logical expressions get
combined into more complex conditions that
are true or false
Relational Operator
⚫ Used to compare two quantities. ⚫ Examples

⚫ < is less than ⚫ 10 > 20 is false, so value is ?

⚫ > is greater than ⚫ 25 < 35.5 is true, so value is ?

⚫ <= is less than or equal to ⚫ 12 > (7 + 5) is false, so value is ?

⚫ >= is greater than or equal to ⚫ 32 !=(10+5) is true, so value is ?

⚫ == is equal to ⚫ 24==(12*2) is true, so value is?

⚫ != is not equal to
Relational Operator

⚫ When arithmetic expressions are used on either side of a relational


operator, the arithmetic expressions will be evaluated first and then the
results compared

⚫ a + b > c – d is the same as (a + b) > (c – d)


Unary Negation
⚫ Unary negation operator (!) ⚫ Examples
⚫ Single operand ⚫ (!10) Value=0
⚫ Value is 0 if operand is non-zero ⚫ (!0) Value = 1
⚫ Value is 1 if operand is 0
Logical and Relational Expressions
⚫ (count <= 100)

⚫ ((math+phys+chem)/3 >= 60)

⚫ ((gender == ’M’) && (age >= 21))

⚫ ((marks >= 80) && (marks < 90))

⚫ ((balance > 5000) | | (no_of_trans >


25))

⚫ (! (grade == ’A’))
Examples
⚫ (4 > 3) && (100 != 200)

⚫ Value?

⚫ (!10) && (10 + 20 != 200)

⚫ Value?

⚫ (!10) || (10 + 20 != 200)

⚫ Value?

⚫ a = 3 && b = 4

⚫ Value?
Examples
⚫ (4 > 3) && (100 != 200)

⚫ Value?

⚫ (!10) && (10 + 20 != 200)

⚫ Value?

⚫ (!10) || (10 + 20 != 200)

⚫ Value?

⚫ a = 3 && (b = 4)

⚫ Value?
Increment and Decrement Operator

+ + or − −
++m; or ++m;
--m; or − −𝑚;
The operator + + add 1 to the operand
The operator − − subtract 1 to the operand
Increment and Decrement Operator

• We use the increment and decrement


operator in mainly for and while
• + +𝑚; is equivalent to 𝑚 = 𝑚 + 1;
• − −𝑚; is equivalent to 𝑚 = 𝑚 − 1;
Increment and Decrement Operator

𝑚 = 5; 𝑚 = 5;
𝑦 =+ +𝑚; 𝑦 = 𝑚 + +;

𝑚 = 6; 𝑚 = 6;
𝑦 = 6; 𝑦 = 5;
Conditional Operator

𝑒𝑥𝑝1 ? 𝑒𝑥𝑝2 ∶ 𝑒𝑥𝑝3


If exp1 then
𝑒𝑥𝑝2;
𝑒𝑙𝑠𝑒
𝑒𝑥𝑝3;
Conditional Operator

𝑎 = 10;
𝑏 = 15;
𝑥 = 𝑎 > 𝑏 ? 𝑎 ∶ 𝑏;
Bitwise Operator

~ One’s complement
& bitwise AND
| bitwise OR
^ bitwise XOR
≪ shift Left
≫ shift right
Example
#include <stdio.h> // The result is 00001100 (12)
int main()
{ printf("a^b = %d\n", a ^ b);
unsigned char a = 5, b = 9;
// a = 5(00000101), // The result is 11111010 (250)
// b = 9(00001001) printf("~a = %d\n", a = ~a);

// The result is 00010010 (18)


// The result is 00000001 (1)
printf("b<<1 = %d\n", b << 1);
printf("a = %d, b = %d\n", a, b);
printf("a&b = %d\n", a & b); // The result is 00000100 (4)
printf("b>>1 = %d\n", b >> 1);
// The result is 00001101 (13) return 0;
printf("a|b = %d\n", a | b); }
Precedence and associativity
Operator class Operator Associativity

Unary Postfix++, -- L to R
High
Unary ++, --Prefix R to L
Binary */% L to R
Binary +- L to R

Binary < <= > >= L to R


Binary == != L to R
Binary && L to R
Binary || L to R
Low Assignment = += -= *= /= %= R to L
Conditional Statement
⚫ Allow different sets of instructions to be executed depending on truth or
falsity of a logical condition
⚫ Also called Branching

How do we specify conditions?


⚫ Using expressions

⚫ non-zero value means condition is true

⚫ value 0 means condition is false

⚫ Usually logical or relational expressions, but can be any expression

⚫ The value of the expression will be used


Branching: The if statement
if (expression) if (expression) {
statement; Block of statements

Compound statements
⚫ A sequence of statements enclosed within { and }

⚫ Each statement can be an assignment statement, control statement,

input/output statement, or another compound statement


⚫ We will also call it block of statements sometimes informally
if selection structure

True
Marks >=70 Print Grade “B”
Print “Passed”

False

Exit
Example1: Largest of three numbers
void main()
{
int a,b,c;
scanf (“%d%d%d”, &a, &b, &c);
if ((a >= b) && (a >= c))
printf (“\n The largest number is: %d”, a);
if ((b >= a) && (b >= c))
printf (“\n The largest number is: %d”, b);
if ((c >= a) && (c >= b))
printf (“\n The largest number is: %d”, c);
}
Example2:Calculation of Bonus
Void main( )
{
int bonus, cy, yoj, yr_of_ser ;
printf ( "Enter current year and year of joining " ) ;
scanf ( "%d %d", &cy, &yoj ) ;
yr_of_ser = cy - yoj ;
if ( yr_of_ser > 3 )
{
bonus = 2500 ;
printf ( "Bonus = Rs. %d", bonus ) ;
}}
Branching: The if-else statement
if (expression)
{
if (expression) Block of statements;
{ }
Block of statements; else if
{
} Block of statements;
else }
else
{ {
Block of statements; Block of statements;
}
}
Example1:Largest of three numbers
void main ()
{
int x, y, z, max;
scanf (“%d%d%d”,&x,&y,&z);
if (x > y)
max = x;
else
max = y;
if (max > z)
printf (“max is %d”, max) ;
else
printf (“max is %d”,z);
}
Example2:Largest of three numbers
/* Calculation of max */ /* Calculation of max */
void main () void main ()
{ {
int x, y, z, max; int x, y, z, max;
scanf (“%d%d%d”,&x,&y,&z); scanf (“%d%d%d”,&x,&y,&z);
if ((x > y) && (x >z)) if ((x > y) && (x >z))
max = x; printf (“Max is %d”, x) ;
else if ((y > x) && (y >z)) else if ((y > x) && (y >z))
max = y; printf (“Max is %d”, y) ;
else else if ((y > x) && (y >z))
max=z; printf (“Max1 is %d”, z) ;
printf (“Max is %d”, max) ;
} }
Branching: The nested if-else statement
if (expression)
if (expression)
{
{
Block of statements;
if (expression)
}
{
else
Block of statements;
{
}
if (expression)
Else
{
{
Block of statements;
Block of statements;
}
}
Else
}
{
else
Block of statements;
{
}
Block of statements;
}
}
Thanks
Any Questions?

You might also like