Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Similar documents
Department of Computer Science

Operators in C. Staff Incharge: S.Sasirekha

Data Types and Variables in C language

Operators and Expressions:

UNIT 3 OPERATORS. [Marks- 12]

Prepared by: Shraddha Modi

Unit 3. Operators. School of Science and Technology INTRODUCTION

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Informatics Ingeniería en Electrónica y Automática Industrial

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Operators and Type Conversion. By Avani M. Sakhapara Assistant Professor, IT Dept, KJSCE

Chapter 3: Operators, Expressions and Type Conversion

UNIT- 3 Introduction to C++

Operators. Java operators are classified into three categories:

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Unit-2 (Operators) ANAND KR.SRIVASTAVA

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basics of Programming

Arithmetic Operators. Portability: Printing Numbers

Constants and Variables

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

JAVA OPERATORS GENERAL

Operators & Expressions

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Chapter 4. Operations on Data

Information Science 1

Expressions and Precedence. Last updated 12/10/18

Computer Programming CS F111

Expression and Operator

Computers Programming Course 6. Iulian Năstac

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Operators in java Operator operands.

C expressions. (Reek, Ch. 5) 1 CS 3090: Safety Critical Programming in C

SECTION II: LANGUAGE BASICS

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Reserved Words and Identifiers

Programming for Engineers Iteration

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

More Programming Constructs -- Introduction

Operators and Expressions

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Programming in C++ 5. Integral data types

A flow chart is a graphical or symbolic representation of a process.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Chapter 7. Additional Control Structures

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Computer System and programming in C

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Prof. Navrati Saxena TA: Rochak Sachan

Engineering Computing I

Fundamentals of Programming

Declaration and Memory

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

CHAPTER 3 Expressions, Functions, Output

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

Bits, Words, and Integers

COMP Primitive and Class Types. Yi Hong May 14, 2015

Java enum, casts, and others (Select portions of Chapters 4 & 5)

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

C++ is case sensitive language, meaning that the variable first_value, First_Value or FIRST_VALUE will be treated as different.

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Fundamental of Programming (C)

Chapter 4: Basic C Operators

Programming. Elementary Concepts

Expressions and Statementst t. Assignment Operator. C Programming Lecture 6 : Operators. Expression

C - Basic Introduction

These are reserved words of the C language. For example int, float, if, else, for, while etc.

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Infix to Postfix Conversion

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Java Notes. 10th ICSE. Saravanan Ganesh

ME 461 C review Session Fall 2009 S. Keres

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

2/5/2018. Expressions are Used to Perform Calculations. ECE 220: Computer Systems & Programming. Our Class Focuses on Four Types of Operator in C

Operators And Expressions

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Work relative to other classes

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Programming I Lecture 7

Basic Source Character Set for C++ Language:

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Transcription:

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Operators and Expressions 8/24/2012 Dept of CS&E 2 Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Comma operators Arithmetic expressions Evaluation of expressions Operator precedence and associativity Type conversions

8/24/2012 Dept of CS&E 3 Operators and Expressions Operator: Symbol that tells the computer to perform certain mathematical or logical manipulations. Expression: Sequence of operands and operators that reduces to a single value. Consists of a single entity, such as a constant or a variable. Consists of some combination of such entities, interconnected by one or more operators.

8/24/2012 Dept of CS&E 4 Arithmetic operators Integer Arithmetic Real Arithmetic Mixed mode Arithmetic Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bit wise operators Special operators Comma Operator sizeof Operator Operator Classification

8/24/2012 Dept of CS&E 5 Arithmetic Operators Operator Meaning + Addition - Subtraction or unary minus * Multiplication / Division % Modulo division Integer division truncates any fractional part Modulo division produces the remainder of an integer division

8/24/2012 6 Arithmetic Operators (contd.) Ex: a-b a%b -a*b Here a and b are variables and are known as operands No operator for exponentiation

8/24/2012 Dept of CS&E 7 Integer Arithmetic When both the operands in a single arithmetic expression such as a+b are integers, the expression is called an integer expression and the operation is called integer arithmetic. Integer arithmetic always yields an integer value. Example: Let a=14 b=4 a-b=10 a+b=18 a*b=56 a/b=3 (decimal part truncated) a%b=2 (remainder of division)

8/24/2012 Dept of CS&E 8 Integer Arithmetic (contd.) Integer Division: If both operands are of the same sign, the result is truncated toward zero. If one of them is negative, the direction of truncation is implementation dependent. Ex: 6/7=0-6/-7=0-6/7 may be zero or -1.(machine dependent)

8/24/2012 Dept of CS&E 9 Integer Arithmetic (contd.) Modulo division: Sign of the result is always the sign of the first operand. (the dividend) -14%3 = -2-14%-3 = -2 14%-3 = 2 Cannot be used on floating point data.

8/24/2012 Dept of CS&E 10 Program to illustrate integer arithmetic #include<iostream.h> #include<conio.h> void main() { clrscr(); int months, days; cout<< Enter days <<endl; cin>>days; months=days/30; days=days%30; cout<< Months= <<months<<endl; cout<< Days= <<days<<endl; getch(); } (i) (ii) Output Enter days 265 Months=8 Days=25 Enter days 364 Months=12 Days=4

8/24/2012 Dept of CS&E 11 Real Arithmetic An Arithmetic operation involving only real operands. A real operand may assume values either in decimal or exponential notation Since floating point values are rounded to the number of significant digits permissible, final value is an approximation of the correct result. Ex: If x, y and z are floats, then x=6.0/7.0=0.857143 y=1.0/3.0=0.333333 z=-2.0/3.0=-0.666667 Operator % cannot be used on real operands

8/24/2012 Dept of CS&E 12 Mixed mode Arithmetic One of the operands is real and the other is integer. Only the real operation is performed and the result is always a real number. Ex: 15/10.0=1.5 15/10=1

8/24/2012 Dept of CS&E 13 Relational Operators Relational operators are used to compare two quantities Operator Meaning < is less than <= is less than or equal to > is greater than >= is greater than or equal to == is equal to!= is not equal to

8/24/2012 Dept of CS&E 14 Relational Operators (contd.) Among the six relational operator each one is a complement of the other > is a complement of <= < is a complement of >= == is a complement of!=

8/24/2012 Dept of CS&E 15 An expression such as a<b containing a relational operator is called a relational expression. Used in decision statements such as if and while to decide the course of action of a running program The value of a relational expression is one, if the specified relation is true and zero if the relation is false. Ex: 10<20 is true 20<10 is false Relational Operators (contd.)

8/24/2012 Dept of CS&E 16 Relational Operators (contd.) A simple relational expression contains only one relational operator and takes the following form. ae1 relational operator ae2 ae1 and ae2 are arithmetic expressions, which may be simple constants, variables or combinations of them.

17 Relational Operators (contd.) Suppose that i, j and k are integer variables whose values are i =1, j = 2 and k = 3 respectively Expression Interpretation Value i < j true 1 (i + j) >= k true 1 (j + k) >(i + 5) false 0 k!= 3 false 0 j == 2 true 1 When arithmetic expressions are used on either side of a relational operator, arithmetic expressions will be evaluated first and then the results compared. That is, arithmetic operators have a higher priority over relational operators.

8/24/2012 Dept of CS&E 18 Logical Operators Operator && Meaning logical AND logical OR! logical NOT The logical operators AND and OR are used when we want to test more than one condition and make decisions. Ex.: (a>b) && (x==10) An expression of this kind which combines two or more relational expressions is termed as a logical expression or a compound relational expression Yields a value of one or zero

8/24/2012 Dept of CS&E 19 Logical Operators Truth Table op-1 op-2 value of expression op-1&&op-2 op-1 op-2 Non-zero Non-zero 1 1 Non-zero 0 0 1 0 Non-zero 0 1 0 0 0 0

8/24/2012 Dept of CS&E Logical Operators Ex.: Suppose int i=7; float f= 5.5; char c= w ; Expression Interpretation Value (i >= 6) && (c == w ) true 1 (i >= 6) (c == w ) true 1 (f < 11) && ( i > 100) false 0 f > 5 true 1!(f > 5) false 0 i <= 3 false 0!(i <= 3) true 1 i > (f+1) true 1!(i > (f+1)) false 0

8/24/2012 Dept of CS&E 21 Assignment Operators Assignment operators are used to assign the result of an expression to a variable. identifier = expression Where identifier represents a variable, and expression represents a constant, a variable or a more complex expression. The variable on the L.H.S is called the target variable.

8/24/2012 Dept of CS&E 22 Ex: a = 3; x = y + 1; area = length * width; Assignment Operators(contd.) The assignment operator = and the equality operator == are different Ex: a=2 is not the same as a==2 If the two operands in an assignment expression are of different types, then the value of the expression on the right will automatically be converted to the type of the identifier on the left. Truncation will result when real value is assigned to an integer

8/24/2012 Dept of CS&E 23 Assignment Operators(contd.) Ex: Suppose i is an integer type variable Expression Value of i i = 3.9 3 i = -3.9-3 Multiple assignments of the form identifier1 = identfier2=... = expression are permitted. In such situations, the assignments are carried out from right to left. Ex: Suppose i, j and k are integer variables. i = j = k = 5; k is assigned value 5 first followed by j and i.

8/24/2012 Dept of CS&E 24 Shorthand assignment operators v op = exp; Where v is a variable, op is a binary arithmetic operator and exp is an expression. v op = exp; is equivalent to v=v op (exp); Shorthand operators have the following advantage What appears on the left side need not be repeated and becomes easier to write Statement is more concise and easier to read Statement is more efficient

8/24/2012 Dept of CS&E 25 Assignment Operators(contd.) Ex: Suppose i = 5, j = 7, f = 5.5, and g = -3.25 i, j are integers, f and g are floating point numbers Expression Equivalent Expression Final Value i += 5 i=i+5 10 f -= g f=f-g 8.75 j *= (i-3) j=j*(i-3) 14 f /= 3 f=f/3 1.833333 i %= (j-2) i=i%(j-2) 0

8/24/2012 Dept of CS&E 26 Increment (++) and Decrement (--) Operators The operator ++ adds 1 to the operand. The operator -- subtracts 1 from the operand. Both are unary operators and requires variables as their operands ++i or i++ is equivalent to i=i+1 They are normally used in for and while loops They behave differently when they are used in expressions on the R.H.S of an assignment statement.

8/24/2012 Dept of CS&E 27 Increment and Decrement Operators(contd.) When postfix (++ or --) is used with a variable in an expression, the expression is evaluated first using the original value of the variable and then the variable is incremented or decremented by one. When prefix (++ or --) is used with a variable in an expression, variable is incremented or decremented first and then the expression is evaluated using the new value of the variable.

8/24/2012 Dept of CS&E 28 Increment and Decrement Operators(contd.) Ex: m = 5; y = ++m; In this case, the value of y and m would be 6. m = 5; y = m++; Here y continues to be 5. Only m changes to 6.

8/24/2012 Dept of CS&E 29 Conditional Operator ternary operator pair? : of the form exp1? exp2 :exp3 where exp1, exp2, exp3 are expressions exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Only one of the expressions (either exp2 or exp3) is evaluated.

8/24/2012 Dept of CS&E 30 Conditional Operator(contd.) Ex.: a=10; b=15; x=(a>b)? a : b; In this example x will be assigned the value of b. The above expression is equivalent to if (a>b) x=a; else x=b;

8/24/2012 Dept of CS&E 31 Bitwise operators Used for manipulation of data at bit level. Used for testing bits or shifting them left or right. Cannot be applied to float or double

8/24/2012 Dept of CS&E 32 Bitwise operators(contd.) Operator & Meaning bitwise AND bitwise OR ^ bitwise exclusive OR << shift left >> shift right

8/24/2012 Dept of CS&E 33 Comma Operator It is used to link related expressions together Comma-linked list of expressions are evaluated left to right and the value of right-most expression is the value of the combined expression Comma has the lowest precedence of all operators and hence parenthesis is necessary

8/24/2012 Dept of CS&E 34 Comma Operator(contd.) Ex.: value = (x=10, y=5, x+y); The statement first assigns 10 to x, 5 to y and then 15 (10+5=15) to value Ex.: for ( n=1, m=10, n<=m; n++,m++) Ex.: while (c=getchar(), c!= 10 )

8/24/2012 Dept of CS&E 35 Arithmetic Expressions It is a combination of variables, constants and operators arranged as per the syntax of the language C does not have operator for exponentiation

8/24/2012 Dept of CS&E 36 Examples of expressions Algebraic expression a X b c C++ expression a * b c ab c x y c (m + n) (x + y) (m + n) * (x +y) a*b / c x/y + c 3x 2 2x 1 3*x*x+2*x+1

8/24/2012 Dept of CS&E 37 Evaluation of expressions Expressions are evaluated using assignment statement of the form variable=expression; Variable is any valid C variable name When statement is encountered the expression is evaluated first and the result then replaces the previous value of the variable on the left hand side All variables used in the expression must be assigned values before evaluation is attempted.

8/24/2012 Dept of CS&E 38 Program to illustrate evaluation of expressions void main() { float a, b, c, x, y, z, f; int d=5; a = 9; f = 7/2; cout << a << endl << f << endl; b = 12.0; c = 3.0; x = a b / 3 + c * 2-1; y = a b / (3 + c) * (2-1); z = a - (b / (3 + c) * 2) - 1; c = a < 5; d = b > d; cout << x = << x << endl; cout << y = << y << endl; cout << z = << z << endl; cout << c << endl << d; getch(); } output: 9 3 x=10 y=7 z=4 0 1

8/24/2012 Dept of CS&E 39 Operator precedence and associativity Each operator has a precedence associated with it Precedence is used to determine how an expression involving more than one operator is evaluated There are distinct levels of precedence and an operator may belong to one of these levels Precedence rule is applied in determining the order of application of operators in evaluating sub-expressions Operators at a higher level of precedence are evaluated first

8/24/2012 Dept of CS&E 40 Operator precedence and associativity(contd.) Operators of same precedence are evaluated either form left to right or from right to left depending on the list of operators, their precedence levels, and their rules of association The order in which operators at the same precedence level are evaluated is known as Associativity. Associativity rule is applied when two or more operators of same precedence level appear in a subexpression Associativity may be from left to right or from right to left depending on the precedence level.

8/24/2012 Dept of CS&E 41 Operator precedence and associativity(contd.) a Two distinct priority levels of arithmetic operators High priority operators * / % Low priority operators + - Ex.: a b/c*d is equivalent to the algebraic formula b [( ) d] c If a =1.0, b = 2.0, c = 3.0 and d = 4.0 then the value is 2.0 1.0 [( ) 4.0] 1.6666666 3.0

8/24/2012 Dept of CS&E 42 Operator precedence and associativity(contd.) Basic evaluation procedure involves two left-to-right passes through the expression. During first pass, high priority operators are applied as they are encountered During second pass, low priority operators are applied as they are encountered

8/24/2012 Dept of CS&E 43 Operator precedence and associativity (contd.) The natural precedence of operations can be altered through the use of parentheses It can also be used to improve the understandability of the program Expression within the parentheses assume highest priority With two or more set of parentheses the expression contained in the leftmost set is evaluated first and the rightmost in the last. ex:(a-b)/(c*d) is equivalent to the algebraic formula (a-b)/(c x d) Parentheses can be nested, one pair within the other. The innermost sub-expression is evaluated first, then the next innermost sub-expression, and so on. ( a b)( c ( e f ) d) is equivalent to ((a + b) * (c + d)) / (e + f)

8/24/2012 44 Operator precedence Groups Operator Category Operators Associativity Unary operators + - + + - -! R L Arithmetic operators * / % L R Arithmetic Operators + - L R Shift Operators << >> L R Relational operators < <= > >= L R Equality operators ==!= L R Bitwise AND & L R Bitwise XOR ^ L R Bitwise OR L R Logical AND && L R Logical OR L R Conditional expression? : R L Assignment operator = += -= *= /= %= R L Comma Operator, L R

8/24/2012 Dept of CS&E 45 Operator precedence and associativity (contd.) Ex: (x==10 +15 && y<10) Assume x=20 and y=5 Evaluation: Step 1:Addition Step 2: < Step 3: == Step 4: && (x==25 && y<10) (x==25 && true) (False && true) (False)

8/24/2012 Dept of CS&E 46 Type conversion C++ permits mixing of constants and variables of different types in an expression, but during evaluation it adheres to very strict rules of type conversion. If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type. The automatic conversion is known as implicit type conversion Conversion Hierarchy Short/char int unsigned int long int unsigned long int float double long double

8/24/2012 Dept of CS&E 47 Type conversion(contd.) Finally result of an expression is converted to the type of the variable on the left of the assignment sign. float to int causes truncation of the fractional part double to float causes rounding of digits long int to int causes dropping of the excess higher order bits

8/24/2012 Dept of CS&E 48 Type conversion(contd.) There are instances when we want to force a type conversion in a way that is different from the automatic conversion. Process of local conversion is known as explicit conversion or casting a value General form is (type-name) expression //C notation type-name (expression) // C++ notation where type-name is one of the standard C++ data type. and expression may be a constant, variable or an expression Ex.: average = sum / (float) i; average = sum/ float (i);

8/24/2012 Dept of CS&E 49 Type conversion(contd.) Ex.: Consider, for example, the calculation of ratio of doctors to engineers in a town. Ratio = doctor_number / engineer _number Suppose doctor _number and engineer_number are declared as integers in the program, the decimal part of the result of the division would be lost and ratio would represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below: Ratio = (float) doctor_number / engineer _number