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

C-programming Operators

This document provides an overview of operators and expressions in C programming, detailing various types of operators including arithmetic, relational, logical, assignment, and bitwise operators. It explains the concept of operands, operator precedence, and the evaluation of expressions, along with examples of how to use these operators in programming. Additionally, it covers type conversions and the use of special operators such as the conditional and size of operators.

Uploaded by

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

C-programming Operators

This document provides an overview of operators and expressions in C programming, detailing various types of operators including arithmetic, relational, logical, assignment, and bitwise operators. It explains the concept of operands, operator precedence, and the evaluation of expressions, along with examples of how to use these operators in programming. Additionally, it covers type conversions and the use of special operators such as the conditional and size of operators.

Uploaded by

Pragista Nepal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
OPERATORS AND EXPRESSION | Chapter Outline ‘er completion of this chapter, you will be able to gain the knowledge and understanding regarding: Arithmetic operator Relational operator Logical or Boolean operator Assignment Operator ‘Ternary operator, Bitwise operator, Increment or Decrement operator, Conditional operator, Special Operators (size of and comma) Evaluation of Expression Operator Precedence and Associativity Scanned wth G camscanner 58 C Programming Operators and Expressions Se ee ee en eames! Operators ‘An operator is a symbol or sign that operates on single or multiple data items and tells the computer to perform certain operations on one or more data items (operands). An operand is q data item that is operated by operator. An operator that requires two operands to operate ig binary (dyadic) operator; an operator that requires only one operand to operate is unary (mono) operator. For example in the expression X + Y, -X, where X and Y are operands and + is binary operator, . is unary operator. Operator Classification According to Number of Operands Unary Operators: The operators which require only one operand are called unary operators, Eg. +4increment operator), --(decrement operator), +(unary plus), and -(unary minus) are unary operators. + Binary Operators: The operators which require two operands are called binary operators, Eg. : Hplus), -(minus), *“(multiply), /(ivision), <(ess than), >(greater than), etc are binary operators. * Ternary Operators: The operators which require three operands are called ternary operators. E.g. the operator pair “? :” (conditional operator) is a ternary operator in C. ‘According to Utility and Action + Arithmetic Operators + Relational Operators = Logical Operators = Assignment Operators + Tnerement and Decrement Operators + Conditional Operators (Ternary Operator) = Bitwise Operators * Special Operators (Comma Operator and sizeof Operator) 1. Arithmetic Operators ‘The operators which are used to manipulate or calculate arithmetic expressions are called arithmetic operators. There are five arithmetic operators in C which are listed in table below ith meaning: Addition X+Y=1345=18 Subtraction K-Y=13-558 * Multiplication [x 13*5=65 1 Division (gives quotient after division) XIY=18/6=2 % | Modulus division (gives remainders after integer | X%Y=18%5=3 division) where X =13and Y=5 are integer numbers ‘Scanned with |CamScanner Operators and Expression O (Chapter 4) 59 Note: = The operands acted upon by arithmetic operators must be numeric values (int, float, etc.). + The division operator requires that the second operand be non-zero. + Integer division truncates any fractional part. + The modulo division operator (remainder operator) requires that both operand be integers and that the second operand be non-zero. + The unary minus operator multiplies its single operand by -1. A program to demonstrate the uses of arithmetic operators print£ ("Enter a “-scanf("td", &a); printf ("Enter b: “scant ("8d", &b); 3 print£("\na+b = 8a", printé("\na-b printé ("\na*b | printf ("\na/b ile 6 44) ‘ printf ("6 8 a= ad\n", Dy 12 = 44% 6; print£("4 3% 6 = ad\n", 2) m3 = 6% 3; printf ("6 tt 3 = Ad\n", 3) Fd = 38 67 i eee: Print£("3 8% 6 = aa\n", . 5 = 183; printf ("1 $% 3 = %d\n", r5); ea Sl sa\n", 16); Scanned with |\CamScanner 60 C Programming Program to jeouvert) number of days into days and month, Program to demonstrate the use of arithmetic operator Scanned with |CamScanner™ Operators and Expression O aI clrser (); f ate er long num, n, digitl, digit2, digit3, digit4, digitS; printf ("Enter a six digit integer a its scanf("$ld", &num); n= num; digitl =n % 10; n=n/ 10; n % 10; centimeters, and millimeters, SURE IEs See 2. Relational operators ‘These operators are used to compare two quantities and depending on their relation, take certain decisions. For example we may compare the salaries of two employees and marks of two students and so on. These types of comparisons are carried out by using relational operators. ‘The operators and their meaning are listed below. Operator ‘Meaning Example < [is tess than KY <= is less than or equal to X<=¥ > is greater than Y > is greater than or equal to XoeY | is equal to = not equal to XIEY where X and Y are two quantities scanned with 3. Logical operators Program that Semonst=sies the use of relatitaall par atins Fane Operators and Expression O (Chapter 4] 63 Logical operators are the combination of relational operator, which represent conditions that are either true or false. The resulting expression will be of type integer, since true is represented by integer value 1 and false is represented by the value 0. C has following three logical operators which are shown in table with meaning. Operators Meaning t && logical AND u logical OR ! logical NOT. opt | op2 | opi && op2 | opi || op2 | topi | top2 o | o 0 0 1 {21 i o [4 0 1 1} 0 1 0 0 1 oO 1 av] oa 1 1 ojo ¥ ‘rogram that demonstrates the. use of logical operators. Scanned with |\CamScanner 64 C Programming 4, Increment and decrement operator | C has two very useful operators not generally found in other languages. These are increment. and decrement operators: + and - -. The operator ++ adds 1 to the operand while - - subtracts 1| Both are unary operator and takes the following form prefix (+x); or postfix (x##) and prefix (| -x); or postfix (x--); +x is same as x =x+1 (or x4=1); - -x is same as x=x-1 (or x-=1); generally we use increment and decrement operators in looping. While ++x and x++ means the same things) when they form statement independently, they behave differently when they are used in ‘expressions on the right-hand side of an assignment statement. Consider the following: x=10;, y=++x; in this case the values of x and y will be 11, Suppose if we write the above statement as_ x=10; y=x+4; in this case the values of x is 11 and y is 10. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on left. On the other hand, postfix) operators first assigns the value to the variable on left and then increment the operand. For prefix and postfix - - operator same rule is applied as above prefix and postfix ++ operator. iw [Operation Interpretation Preincrement mo Postincrement Predecrement Postdecrement 5, Assignment Operators Assignment operators are used to assign values of an expression to a variable. In C the usual assignment operator is =. In addition, C has a set of shorthand assignment operators of the form variable operator=expression; the operator is the C binary arithmetic operator. The operator= is known as shorthand assignment operator. For example if you evaluate the expression: int a=4, b=6, e=10; a=btc; then the value of a (which is 4) will be replaced by 16 (which is 6+10). ‘Then the calculation is performed at right hand side of the equal sign and replaces the value at left hand variable. Consider an another example: x + =z-6; this is same as x=x + (2-5). The shorthand operator + = means add z -5 to x or increment x by z -5. For z=7, the above statement becomes x +=2; and when this statement is executed , 2 is added to x. If the old value of x is 2 then the new value is 4. Some of the commonly use shorthand assignment operators as follows Simple assignment operator Shorthand operator p=p+1 p+=1 pp-l Sg p= P=p *(q +5) p*=qt5 p=p/(q+5) p/=q+5 Pp %5 p%= 6. Conditional Operators It is also known as ternary operator. A ternary operator pair “?:” is available in C to construct conditional expressions of the form: expl?exp2:exp3; where expl, exp2 and exp3 are expressions. The operator? : works as follows; first evaluate exp1, if exp] is true then evaluate exp2, If exp] is false then execute exp3. Note that only one of the expressions (either exp2 or exp3) is evaluated. Consider the following statement Scanned wth G camscanner Operators and Expression O (Chapter 4] 65 example, z will be assigned the value of y because the value of y is larger ‘than value of x. This operator is same as the function of if else statement. Program that finds the larger among two integers using conditional operator. = tiedvss: atte = 7. Comma Operator (,) It is also special type of operator used in C. It is used to separate the identifiers/expressions, variable declaration, linked list of expression and also be used in for loop. These examples ‘illustrates the use of comma (,) operator. 8. _ Bitwise Operators Bitwise Operators are used for manipulating data at bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators can be applied only to integer ‘type signed or unsigned) and not to float or double. The bitwise operators are in C are as follows: Operator Meaning 3 & Bitwise AND b L Bitwise OR * Bitwise exclusive OR << Left shift >> Right shift ~ Bitwise one’s complement operator Bitwise Complement (~) is the unary operator and produces a value with each bit of the ‘operand inverted. For example : 1101 0011 becomes 0010 1100. Bitwise AND (&) is AND and produces a value in which each bit is set to 1 only if both ‘corresponding bits in the two operands are 1, For example: 10110010 (178) 00110010 (60) Scanned with |\CamScanner os 66 © C Programming 4 Bitwise OR(I) is OR and produces a value in which each bit is set to 1 if either, or both, corresponding bits of the two operands are 1. For Example : 1011 0010 (178) —L__0000 1000 _(63) = 10111010 (186) Bitwise exclusive OR (*) is EXCLUSIVE OR and produces a value in which each bit is set to 1 only if one or the other (but not both) of the corresponding bits of the two operands is 1. For Example: 10110010 (478) *__* __0011 1109 __(63) = 1000 1110 (142) Program that demonstrates the use of bitwise logical operators. Left shift (<<) is left-shift and produces a value obtained by shifting the bits of the left-hand operand to the left by the number of places given by the right-hand operand. Vacated slots are filled with zeros. The left shift operator is used in the for In the following expression the value in the variable “a” is shift by 2 bits to left: Right shift(>>) is right-shift and produces a value obtained by shifting the bits of the left-hand operand to the right by the number of places given by the right-hand operand. For unsigned integers; the vacated slots are filled with zeros. The behavior for signed values is | implementation dependent. The right shit the form: Scanned with |\CamScanner Operators and Expression O (Chapter 4] 67 ‘The bitwise operators are most commonly used in system level programming where individual bits of an integer will represent certain real life entities which are either on or off, one or zero. The programme will need to be able to manipulate individual bits directly in these situations. A mask variable which allows us to ignore certain bit positions and concentrate the operation only on those of specific interest to us is almost always used in these situations. The value given to the mask variable depends on the operator being used and the result required. Program that demonstrates the use of use of bitwise shift operators | ¥include #include void main() sake t int numl = 57; int left, right; | clrser(); é A left numl << 3; right numl >> 3; printf ("Left=> %d”, left); print£(*\nRight=> $d”, right); getch (); ‘ } : 9. The size of operator This is the unary operator which finds out number of bytes that any object occupies in computer’s memory. It has the same precedence and associative as other operator. It looks like a function but really an operator. The syntax of sizeof operator is sizeof (object); For example int x; float y; char name; then sizeof (x),sizeof(y) and sizeof (name) gives the size of integer, sizeof floating and sizeof character. Program that demonstrates the use of sizeof() operator. #include = ~ #include aie void main() ides int num; elrser(); printf ("integer Occupies=> %d bytes\n", sizeof (num)); Print£("double Constant Occupies=> %d bytes\n", sizeof (16.18))? print£("long int Data Type Qualifier Occupies=> $d bytes\n", sizeof (15L))7 : printf ("float Data Type Occupies=> %d bytes", sizeof (15.3£)); yetch (); G camscanner 68) —C Programming Expressions Any arrangement of variable and operators that specifies a computation is called an expression. Expression can also represent logical conditions that are either true or false. For example atbic, x=atb+4, a=b. In C an expression is anything that evaluates to a numeric value. Type Conversions in Expressions In an expression involving operands of two different types, the compiler implicitly converts the operands of two different types. This conversion is not transparent to the programmer and is done quietly by the compiler. In general, type conversions involve converting a narrow type to the wider types so that loss of information is avoided. We can classify type conversion in two groups. 1. Automatic type conversion (Implicit type conversion) 2. ‘Type cast (Explicit type conversion) 1. Automatic type conversion In implicit type conversion, during evaluation, if the operands are of different types, the ‘lower’ type is automatically converted to the ‘higher’ type before the operation proceeds and the result is of the ‘higher’ type. This type of conversion is automatically done by compiler at the time of compilation. The following rule will be used to convert data types automatically. Example: float x; int a; double b; long double 1; ‘The automatic i conversion of the wig b*a /1+ +x is illustrated in the al table pb * a double int double (b * a)/1_ double long double long. double: (b* a)/l__+x long double float long double. 2. Explicit type conversion Sometimes, a programmer needs to convert a value from one type to another in a situation where the compiler will not do it automatically. It is done by programmer as per need to convert one type to another is ealled explicit type conversion. It is also known as type cast in which type conversion. To perform a cast, following syntax is used. (data type) expression; For example: p is of int type and it is needed to be converted into float type then pe resee wai ‘The value of p will remain unchanged but type will be changed. For example if value of p = 10 then after cast its value will be 10.0. Scanned with |\CamScanner Operators and Expression O 69 Some examples of casts and their actions are listed below [Expression Action x = (int) 7.5 17.5 is converted to integer by truncation, a= (int) 21.6/(int) 4.5 Evaluated 21/4 and result would be 5. (double) sum/n int) a+b Precedence and Associativity of Operators division is done in floating point mode, tho result of a+b is converted to integer. Each operator in C has precedence (priority) related with it. This precedence is used to evaluate how a mixed expression involving more than one operator is evaluated. There are distinct level of precedence and an operator may belong to one of these levels. The operators at higher levels of precedence are evaluated first. This priority of operators to evaluate in an expression having different level of operators is called precedence, The operators of the same precedence of are evaluated either from left to right or from right to left depending on the level. This is known as associativity priority of operator. The operators with its precedence and associativity are listed in table. Precedence level! Operators Assiciativity 1 on. [Left to right 2 | ~++-- (unary) ~ (unary) *(unary) &{unary) (type) sizeof _[Right to left 3 (binary) (binary) % [Left to right 4 (pinay) — (binary) [Left to right 5 [Left to right 6 [Left to right 7 \Left to right 8 [&& (logical AND) [Left to right 9 11 Gogical OR) [Left to right 10 [Right to left iL = << >= &=%= [Right to left 2 | (comma) [Left to right Let us consider another example Z=(x/(y-2) +p)*q In this case of evaluating expression Z=(u(y-2) +p)*q. First evaluate (y-2) then this difference will divide to x and result is added to p. Finally the total result is multiplied by a. Evaluate the following expression 278/4+4/448.245/8 Solution: Stepwise evaluation of above expression 2*8/4+4/448-2+5/8 =6/4+4/448-245/8 operator * is evaluate +4/4+8-245/8 operator / is evaluate =14148-2+5/8 operator /is evaluate operator / is evaluate operate + is evaluate operator + is evaluate operator — is evaluate operator + is evaluate ‘Scanned with |CamScanner C Programming = ame 14. 15. 16. 17. ‘What do you mean by operators? Explain arithmetic operators Explain unary operator, binary operator and ternary operator with example. What are the types of C operators? Compare unary and binary operators. What is pre-increment and post-increment? Explain with example. What do you mean by logical operators? Explain How relational operators differ from logical operators? Explain logical operator and bitwise logical operators with example. What do you mean by ternary operator? Explain with example. What is type conversion? Explain implicit and explicit type conversion. ). Define operator precedence and associativity with example. . What do you mean by bitwise shift operator? Explain left shift and right shift operator with example program. . What is automatic type conversion? List the automatic type conversion rule in C. 3. What value does x contain after each of the following where x is of type float? =1+3*6/2- 2%2+2*2-2/2; (8 *9*(34(4*5/3))); =12.0+2/5* 100 Write a program to find the sum of the 4 digit number reading from user. Find the value of following expressions: int a=8, b=5; float x = 0.005, y = 0.01; @ —-2* (@5) + (4*0 - 3))% (atb- 2); @) &>y)&&@>0) 11 <4); @>b)? ab; Find the value of 'a' in each of the following statements: int i=3, j=4, k=8; float a=4.5, b=6.5, c=3.5; @) +i fk + clk: @) a=OWh+G+ohk © - G++ ae +i) @ -i+ je +i*b © +5% 24 © (& + 2)% (+ 3) Write a program to find the value of ‘a’ in each of the following statements with the given initial values int i=2, j=5,k=7; float a=1.5, +5 and c=3.5 a) a=c - i/j + c/k; b) a = (c - i)/k + (3 + b)/ie c) a= b*b - ((I + 3)/e)7 d) a=b-k + j/k + itez ey a=ct+ kt 2+ b; f) a= (b + 1)% (c + 1); aoo Scanned wth G camscanner

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy