Professional Documents
Culture Documents
CS101x S408 Assignment Statement and Arithmetic Expressions IIT Bombay
CS101x S408 Assignment Statement and Arithmetic Expressions IIT Bombay
CS101x S408 Assignment Statement and Arithmetic Expressions IIT Bombay
Computer Programming
Dr. Deepak B Phatak
Dr. Supratik Chakraborty
Department of Computer Science and Engineering
IIT Bombay
Session: Assignment Statement and Arithmetic Expressions
• Assignment statement
• Arithmetic expressions
• General form
Our friendly program:
destination = expression;
• Compute the value of expression and
int main() {
store in destination
int A, B, C;
• Destination
• Variable, for now cout << Gi e t o u ers ;
• Has a declared type cin >> A >> B; C is assigned
the value of
• More ad a ed thi gs later… C = A + B; A+B
• = in C++ assignment statement cout << “u is << C;
NOT SAME AS equality in maths return 0;
• C = C + 1 meaningful in C++, not in maths }
• A + B = C meaningful in maths, not in C++
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 4
Assignment Statement
IIT Bombay
• Expression
• Refers to values of variables Our friendly program:
• Refers to operators
• Evaluates to a value int main() {
• A value must have a type int A, B, C;
How much memory to store? cout << Gi e t o u ers ;
How to interpret stored bits? cin >> A >> B; Arithmetic
• So an expression has a type C = A + B; Expression
• Normally, destination and cout << “u is << C;
expression types match return 0;
• C is int, A + B is int }
• Rule of thumb:
E pressio t pe at least as e pressi e as opera d t pes,
but no more
float a and int b
• float ore e pressi e tha int
• a + b, a – b, a * b, a/b are all float, 2 * b is int, 2.0 * b is float
• double a, float b and int c
• double ore e pressi e tha float
• float ore e pressi e tha int
• a + (b * c) has type double
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 7
Type and Value of Arithmetic Expression
IIT Bombay
int a, b, c; int a;
a = 1; b = 2; float b, c;
c = a/b; a = 1; b = 2.0;
c = a/b;
Type of a/b: int Type of a/b: float
Value of a/b: 0 Value of a/b: 0.5
(integer part of 1/2) (float can represent fractions)
• What is a + b * c + d?
• a + (b*c) + d or (a + b) * (c + d) or ((a + b) * c ) + d ?
• Depends on operator precedence
In C++, * has higher precedence than +: a + ( b * c ) + d
• What is a + b – c + d?
• (a + b) – (c + d) or (a + (b – c)) + d?
• In C++, + and – have same precedence: ( ( a + b ) – c ) + d
• For now, left-to-right evaluation for same precedence operators
Left-associative e eptio s later i ourse …
• *, / and % have same precedence, and are left-associative:
((a % b) / c )* d Different from usual algebra?
• Best pra ti e: Use … to spe ify u a iguously
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 9
Use of Parentheses …
IIT Bombay