40
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER VINAY ALEXANDER ( ( वववव ववववववववववव वववव ववववववववववव ) ) PGT(CS) ,KV JHAGRAKHAND PGT(CS) ,KV JHAGRAKHAND

CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND

Embed Size (px)

Citation preview

  • CHAPTER:8OPERATORS AND EXPRESSION IN C++Prepared By :VINAY ALEXANDER ( )PGT(CS) ,KV JHAGRAKHAND

  • => OPERATORS: An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables=>The objects of the operation(s) are referred to as Operands.Ex: a+b

    operands Operator

  • Arithmetic Operators

    =>Unary Operator: It act on one operand .=> Unary +: The operator unary + precedes an operand.Example: if a=5 then +a means 5.=> Unary -: The operator unary - precedes an operand.Example: if a=5 then -a means -5.

  • Arithmetic Operators=>Arithmetic operators +, -, * are the same as in math =>Division operator / if used on integers returns integer (without rounding) or exception=>Division operator / if used on real numbers returns real number or Infinity or NaN=>Remainder operator % returns the remainder from division of integers.If nominator is less than denominator then remainder is always the nominator value.=> Binary Operator: It act upon two operands .

  • Arithmetic operators

    OperatorDescriptionExample+Adds two operandsA + B will give 30,if A=20 and B=10-Subtracts second operand from the firstA - B will give -10*Multiply both operandsA * B will give 200/Divide numerator by de-numeratorB / A will give 2%Modulus Operator and remainder of after an integer divisionB % A will give 0++Increment operator, increases integer value by oneA++ will give 11--Decrement operator, decreases integer value by oneA-- will give 9

  • Increment(++) & Decrement( ) OperatorsC++ supports 2 useful operators namelyIncrement ++Decrement operators=>The ++ operator adds a value 1 to the operand=>The operator subtracts 1 from the operand++a //pre-increment a++ //post-increment a //pre- Decrementa //post- Decrement

  • Rules for ++ & -- operatorsThese require variables as their operandsThe postfix either ++ or operators follow use-then-change rule i.e., they first use the value of their operand in evaluating the expression and then change(++/ ) the operand value .The prefix either ++ or operators follow change-then-use rule i.e., they first change(++/ ) the value of their operand, then use the new value in evaluating the expression.Note: In Turbo C++, First all prefix operators are evaluated prior to expression evaluation.

  • Examples for ++ & -- operators

    Let the value of a =5 and b=++a thena = b =6Let the value of a = 5 and b=a++ thena =6 but b=5i.e.: 1. a prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left2. a postfix operator first assigns the value to the variable on left and then increments the operand.

  • Q.1: Evaluate z=++x + x++ if x=10 initially.Output:22Q.2.Find the output of the following code segment.int n=7;cout
  • Relational Operators: The relational operators determine the relation among different operands.

    OperatorMeaning=Is greater than or equal to==Equal to!=Not equal to

  • OperatorDescriptionExample==Checks if the value of two operands is equal or not, if equal then condition becomes true.(A == B) is true. !=Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.(A != B) is true. >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is true. =Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is true.

  • Logical Operators: There are following logical operators supported by C++ languageLogical expression or a compound relational expression: An expression that combines two or more relational expressions Ex: if (a==b && b==c)

    OperatorMeaning&&Logical AND||Logical OR!Logical NOT

  • operatorDescriptionExample&&Called Logical AND operator. If both the operands are non zero then condition becomes true.(A && B) is false. If any input values is zero ||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(A || B) is true. !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

  • Truth Table

    abValue of the expressiona && ba || b0000010110011111

  • Conditional(Ternary) operatorsSyntax:exp1 ? exp2 : exp3Where exp1,exp2 and exp3 are expressionsWorking of the ? Operator:Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated and this becomes the value of the expression,If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the expressionEx: m=2; n=3 r=(m>n) ? m : n;Output: r=3

  • Assignment Operators:

    OperatorDescriptionExample=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A> 2&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

  • Special operatorsComma operator ( ,)sizeof operator sizeof( )Pointer operators ( & and *)Member selection operators ( . and ->)

  • OperatorDescriptionsizeofsizeof operator returns the size of a variable. For example sizeof(a), where a is integer, will return 2.,Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.. (dot) and -> (arrow)Member operators are used to reference individual members of classes, structures, and unions.&Pointer operator & returns the address of an variable. For example &a; will give actual address of the variable.*Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

  • Precedence of operators: Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:=>BODMAS RULE: Brackets of Division Multiplication Addition SubtractionBrackets will have the highest precedence and have to be evaluated first, then comes of , then comes division, multiplication, addition and finally subtraction.C++ language uses some rules in evaluating the expressions and they r called as precedence rules or sometimes also referred to as hierarchy of operations, with some operators with highest precedence and some with least.The 2 distinct priority levels of arithmetic operators in c++ are-Highest priority : * / %Lowest priority : + -

  • Rules for evaluation of expressionFirst parenthesized sub expression from left to right are evaluated.If parentheses are nested, the evaluation begins with the innermost sub expressionThe precedence rule is applied in determining the order of application of operators in evaluating sub expressionsThe associatively rule is applied when 2 or more operators of the same precedence level appear in a sub expression.Arithmetic expressions are evaluated from left to right using the rules of precedenceWhen parentheses are used, the expressions within parentheses assume highest priority

  • Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

    CategoryOperatorAssociativityPostfix() [] -> . ++ - -Left to rightUnary+ - ! ~ ++ - - (type)* & sizeofRight to leftMultiplicative * / %Left to rightAdditive + -Left to rightShift >Left to rightRelational < >=Left to rightEquality == !=Left to rightBitwise AND&Left to rightBitwise XOR^Left to rightBitwise OR|Left to rightLogical AND&&Left to rightLogical OR||Left to rightConditional?:Right to leftAssignment= += -= *= /= %=>>=

  • Example 1Evaluatex1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5, c=6=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)=(5 + sqrt((-5)(-5)-4*1*6))/(2*1)=(5 + sqrt(25 -4*1*6))/(2*1)=(5 + sqrt(25 -4*6))/(2*1)=(5 + sqrt(25 -24))/(2*1)=(5 + sqrt(1))/(2*1)=(5 + 1.0)/(2*1)=(6.0)/(2*1)=6.0/2 = 3.0

  • Arithmetic ExpressionsRelational ExpressionsCompound Expressions

  • Arithmetic Expressions can either be integer expressions or real expressions. Sometimes a mixed expressions can also be formed which is a mixer of real and integer expressions.

  • Integer Expressions are formed by connecting integer constants and/or integer variables using integer arithmetic operators. The following are valid integer expressions :int I,J,K,X,Y,Z,count;A) k - xB) k + x y + countC) j + k * yD) z % y

  • Real Expressions are formed by connecting real constants and/or real variables using real arithmetic operators. The following are valid real expressions:float qty,amount,,value;double fin,inter; const bal=250.53; i) qty/amountii) (amount + qty*value)-baliii) fin + qty* interiv) inter (qty * value) + fin

  • The process of converting one predefined type into another is called Type Conversion.C++ facilitates the type conversion in two forms:

  • An implicit type conversion is a conversion performed by the compiler without programmers intervention. An implicit conversion is applied generally whenever differing data type are intermixed in an expression, so as not to lose information.

  • An explicit type conversion is user-defined that forces an expression to be of specific type.

  • The C++ compiler converts all operands upto the type of the largest operand, which is called Type Promotion.

  • The explicit conversion of an operand to a specific type is called type casting.

  • The expressions that result into 0(false) or 1(true) are called logical expressions. The logical expressions are combination of constants, variables and relational operators.

  • A Logical Expressions may contain just one signed or unsigned variable or a constants, or it may have two or more variables or/and constants, or two or more expressions joined by valid relational and/or logical operators. Two or more variables or operators should not occur in continuation.

  • An expression is composed of one or more operations. An expression terminated by semicolon(;) becomes a statement. Statements form the smallest executable unit within a C++ program.An assignment statement assigns value to a variable. The value assigned may be a constant, variable or a expression.Example: a=cve;

  • The value of the right side (expression side) of the assignment is converted to the type of the left side (target variable).=> int x; char ch;ch=x;

  • C++ offers special shorthands that simplify the coding of a certain type of assignment statement.Following are some example of C++ shorthands:x - = 10 ; equivalent to x = x 10;x * = 3 ; equivalent to x = x * 3;x / = 2 ; equivalent to x = x/2 ;x % = z ; equivalent to x = x % z ;

  • =>END

    *