6 operators-in-c

53
OPERATORS IN C

Upload: rohit-shrivastava

Post on 27-Jan-2017

532 views

Category:

Software


1 download

TRANSCRIPT

Page 1: 6 operators-in-c

OPERATORS IN C

Page 2: 6 operators-in-c

C operators

To build an expression, operators are used with operands like 4 + 5, Here, 4 and 5 are operands and ‘+’ is operator

C contains following group of operators –1) Arithmetic2) Assignment3) Logical/Relational4) Bitwise5) Odds and ends

2

Page 3: 6 operators-in-c

Arithmetic Operators

3

Pre increment/Decrement (++i or --i):First increment/decrement current value by 1 and then use the incremented/decremented valuePost increment/Decrement (i++ or i--):First use the current value and then increment/decrement current value by 1 for nexttime use

Page 4: 6 operators-in-c

Arithmetic operators Example#include<stdio.h>void main(){int i=7,j=5;printf(“%d %d %d %d \n”,i+j,i-j,i*j,i/j); 12 2 35

1 printf(“%d \n”,i%j); 2printf(“%d %d \n”,i++,++j); 7 6}

4

Page 5: 6 operators-in-c

Assignment Operators• Each expression contains two parts: lvalue and rvalue,• Arithmetic operations are performed to calculate

rvalue,• Assignment operators are used to assign the rvalue to

lvalueExample:i=i+1can also be reduced toi+=1

5

Page 6: 6 operators-in-c

Assignment Operators Example

6

Page 7: 6 operators-in-c

Relational Operators

7•If condition is true it returns 1 else returns 0.

a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. 

Page 8: 6 operators-in-c

Relational Operators (Cont..)#include<stdio.h>void main(){int i=7,j=1,k=0;printf(“%d \n”,i==j); 0printf(“%d \n”,i<j); 0printf(“%d \n”,i>j); 1printf(“%d \n”,i<=j); 0printf(“%d \n”,i>=j); 1printf(“%d \n”,i!=j); 1}

8

Page 9: 6 operators-in-c

Relational Operators (Cont..)/* C program to find largest number using if...else statement */ #include <stdio.h> int main(){ float a, b, c;

printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c);

if (a>=b) { if(a>=c)

printf("Largest number = %f",a); else

printf("Largest number = %f",c); }

else { if(b>=c)

printf("Largest number = %f",b); else

printf("Largest number = %f",c); }

return 0; }

9

Page 10: 6 operators-in-c

Logical Operators Allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a

true or false value. Logical operator returns 0 or 1. The Logical operators are: &&, || and ! op1 && op2-- Performs a logical AND of the two operands. op1 || op2-- Performs a logical OR of the two operands. !op1-- Performs a logical NOT of the operand. Op1 and op2 may be one condition or single operand C considers non-zero value to true and zero to false. Examples:(a>b)&&(a>c) , a&&b, 5&&8 etc.

10

Page 11: 6 operators-in-c

&&(Logical AND)The && operator is used to determine whether both

operands or conditions are trueFor example:A=50,b=9 if (a == 10 && b == 9)

printf(“Hello!"); If either of the two conditions is false or incorrect, then the printf

command is bypassed. Ex2: if(0&&9)

printf(“Correct !”); else printf(“Incorrect !”);

11

Page 12: 6 operators-in-c

Example of Logical operator

12Output:

Page 13: 6 operators-in-c

|| (Logical OR) The || operator is used to determine whether either of the condition is true. For example: A=50,b=9 if (a== 10 || b == 9) // either of the condition should be true for printing hello!

printf(“Hello!"); If both of the two conditions are false, then only the printf command is bypassed.

Ex2: if(0||9) printf(“Correct !”); else printf(“Incorrect !”);

Caution: If the first operand of the || operator evaluates to true, the second operand will not be evaluated. This could be a source of bugs if you are not careful.

For instance, in the following code fragment: if (9 || X++) { print(“X=%d\n“,X); } variable X will not be incremented because first condition is

evaluates to true.

13

Page 14: 6 operators-in-c

! (Logical NOT)The ! operator is used to convert true values to false

and false values to true. In other words, it inverts a value

For example:A=50,b=9 if (!(a== 10)) //

printf(“Hello!");

Ex2: if(!(0||9)) printf(“Correct !”); else printf(“Incorrect !”);

14

Page 15: 6 operators-in-c

Bitwise Operators

15

•In the C programming language, operations can be performed on a bit level using bitwise operators.•Following are the bitwise Operators

Page 16: 6 operators-in-c

Bitwise AND

16

•A bitwise AND takes two binary representations of equal length and performs the logical AND operation on each pair of corresponding bits. •The result in each position is 1 if the first bit is 1and the second bit is 1; otherwise, the result is 0.•Example: a=5, b=3;• printf(“%d”,a&b); will print 1• 0101--5• & 0011--3

0001--1

•& operation may be used to determine whether a particular bit is set (1) or clear (0). For example, •given a bit pattern 0011 (decimal 3), to determine whether the second bit is set we use a bitwise AND with a bit pattern containing 1 only in the second bit:• 0011 (decimal 3) • & 0010 (decimal 2) • 0010 (decimal 2)

Page 17: 6 operators-in-c

Bitwise OR(|)

17

•A bitwise OR takes two bit patterns of equal length and performs the logical inclusive OR operation on each pair of corresponding bits. •The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits are 1; otherwise, the result is 0. For example: Example: a=5, b=3;• printf(“%d”,a|b); will print 7• 0101--5• | 0011--3

0111--7

•A bitwise XOR(^) takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. •The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. •printf(“%d”,a^b); will print 6• 0101--5• ^ 0011--3

0110--6

Page 18: 6 operators-in-c

shift Operator Left Shift Operator (<<):The left shift operator will shift

the bits towards left for the given number of times.int a=2<<1;Printf(“%d”,a);//If you left shift like 2<<2, then it will give the result as 8. Therefore left shifting 1 time, is equal to multiplying the

value by 2.Right shift Operator ( >>)The right shift operator will shift the bits towards right for

the given number of timesint b=4>>1printf(“%d”,b);// Right shifting 1 time, is equivalent to dividing the

value by 2.18

will print 4

will print 2

Page 19: 6 operators-in-c

Bitwise Operators Example

19

Page 20: 6 operators-in-c

Odds and Ends Operators

20

There are few other important operators including sizeof and ? : supported by C Language.

Page 21: 6 operators-in-c

Examples of sizeof()#include <stdio.h>main() {int a = 4;float b=50.45;char c;printf("Size of variable a = %d\n", sizeof(a) );printf("Size of variable b = %d\n", sizeof(b) );printf("Size of variable c= %d\n", sizeof(c) );printf("Size of 233= %d\n", sizeof(233) );printf("Size of 20.55= %d\n", sizeof(20.55) );printf("Size of 'y'= %d\n", sizeof('y') );printf("Size of unsigned int= %d\n", sizeof(unsigned int) );}

21

Page 22: 6 operators-in-c

Examples of conditional operator(Ternary Operator)main() { int a , b,c;a = 10; b = (a == 1) ? 20: 30; printf( "Value of b is %d\n", b ); c = (a == 10) ? 20: 30; printf( "Value of c is %d\n", c ); }

22

Page 23: 6 operators-in-c

Operators available in C can be classified in following way:

1. unary – that requires only one operand.For example: &a, ++a, *a ,--b etc.

2. binary - that requires two operands. For example: a + b, a * b, a<<2

3. ternary - that requires three operands. For example: (a>b) ? a : b [ ? : ]

Page 24: 6 operators-in-c

24

Precedence and associativity

•Associativity indicates in which order two operators of same precedence (priority) executes.

•If more than one operators are involved in an expression then, C language has predefined rule of priority of operators. This rule of priority of operators is called operator precedence.

Page 25: 6 operators-in-c

25

•precedence of arithmetic operators(*,%,/,+,-) is higher than relational operators(==,!=,>,<,>=,<=) and precedence of relational operator is higher than logical operators(&&, || and !). 

Examples of precedence of operators

Page 26: 6 operators-in-c

26

a==b!=c

Here, operators == and != have same precedence. The associativity of both == and != is left to right, i.e, the expression in left is executed first and execution take pale towards right. Thus, a==b!=c equivalent to :

(a==b)!=c

Ex2Associativity is important, since it changes the meaning of an expression. Consider the division operator with integer arithmetic, which is left associative4 / 2 / 3 (4 / 2) / 3 2 / 3 = 0 If it were right associative, it would evaluate to an undefined expression, since you would divide by zero4 / 2 / 3 4 / (2 / 3) 4 / 0 = undefined

Example of Associativity of Operators

Page 27: 6 operators-in-c

27

i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8

i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /i = 1 + 1+ 8 - 2 + 5 / 8 operation: /i = 1 + 1 + 8 - 2 + 0 operation: /i = 2 + 8 - 2 + 0 operation: +i = 10 - 2 + 0 operation: +i = 8 + 0 operation : -i = 8 operation: +

What will be the value of i

Page 28: 6 operators-in-c

28

•Although Arithmetic instructions look simple to use one often commits mistakes in writing them. •following points should keep in mind while writing C programs:(a)C allows only one variable on left-hand side of = That is, z =k * l is legal, whereas k * l = z is illegal.(b)Other than division operator(/) C has modulus operator(%).Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0.• Note that the modulus operator (%) cannot be applied on a float. •Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.(c) An arithmetic instruction is often used for storing character constants in character variables.char a, b, d ;a = 'F' ;b = 'G' ;d = '+' ;When we do this the ASCII values of the characters are stored in the variables. ASCII values are used to represent any character in memory. The ASCII values of ‘F’ and ‘G’ are 70 and 71.

Arithmetic expressions vs C expressions

Page 29: 6 operators-in-c

29

(d) No operator is assumed to be present. It must be written explicitly. In the following example, the multiplication operator after b must be explicitly written.a = c.d.b(xy) usual arithmetic statementb = c * d * b * ( x * y ) C statement(e) Unlike other high level languages, there is no operator for performing exponentiation operation. Thus following statements are invalid in C.a = 3 ** 2 ;b = 3 ^ 2 ;If we want to do the exponentiation we have pow() function in C:#include <math.h>main( ){int a ;a = pow ( 3, 2 ) ;printf ( “a=%d”, a ) ;// will print 9}Here pow( ) function is a standard library function. It is being used to raise 3 to the power of 2. #include <math.h> is a preprocessor directive. It is being used here to ensure that the pow( ) function works correctly.

Arithmetic expressions vs C expressions(cont..)

Page 30: 6 operators-in-c

30

Arithmetic expressions vs C expressions(cont..)

Page 31: 6 operators-in-c

31

Example-1 #include<stdio.h>void main(){int i=1,j=1;i=2+2*i++;printf(“i=%d",i);printf(“\n%d”,2+2*j++);}Example-2#include<stdio.h>void main(){int a=2,b=7,c=10;c=a==b;printf(“c=%d",c);}

i=54

c=0

Examples Based on Operators

Page 32: 6 operators-in-c

32

•In a C program, comma is used in two contexts: (1) A separator (2) An Operator. •int a=1, b=2, c=3, i=0; // commas act as separators in this line, not as an operator •i = (a, b); // stores b into i •i = a, b; // stores a into i. Equivalent to (i = a), b; •i = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into i •i = a += 2, a + b; // Equivalent to (i = (a += 2)), a + b; •i = a, b, c; // Equivalent to (i=a),b,c•i = (a, b, c); // stores c into i, discarding the unused a and b rvalues •return a=4, b=5, c=6; // returns 6, not 4, •return 1, 2, 3; // returns 3, not 1.•return(1), 2, 3; // returns 3, not 1.

Comma Operator

Page 33: 6 operators-in-c

printf() Function prinf(print formatted) writes to the standard output

(stdout) a sequence of data formatted as the format argument specifies.

void main(){int a,b;printf(“Enter value of a and b number:\n”);scanf(“%d%d”,&a,&b);printf(“you have entered a=%d and b=%d\n”,a,b);} Following is format string for different format: %[flags][width][.precision][length]specifier On success, Printf returns the total number of characters written is returned. On failure, a negative number is returned

Page 34: 6 operators-in-c

specifier Output Example

c Character ad or i Signed decimal integer 392

e Scientific notation (mantissa/exponent) using e character 3.9265e+2

E Scientific notation (mantissa/exponent) using E character 3.9265E+2

f Decimal floating point 392.65g Use the shorter of %e or %f 392.65G Use the shorter of %E or %f 392.65o Signed octal 610s String of characters sampleu Unsigned decimal integer 7235x Unsigned hexadecimal integer 7faX Unsigned hexadecimal integer (capital letters) 7FA

p Pointer address B800:0000

% A % followed by another % character will write % to stdout.

Page 35: 6 operators-in-c

length description

h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

lThe argument is interpreted as a long int or unsigned long int

for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s.

L The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

Page 36: 6 operators-in-c

36

Precision•The "precision" modifier is written ".number", and has slightly different meanings for the different conversion specifiers (like d or g).•For floating point numbers (e.g. %f), it controls the number of digits printed after the decimal point:•printf( "%.3f", 1.2 ); will print 1.200 •If the number provided has more precision than is given, it will round. For example:•printf( "%.3f", 1.2348 ); will display as 1.235 •printf( "%.3f \n%.3g \n%.3f \n%.3g \n", 100.2, 100.2, 3.1415926, 3.1415926 );•Output:•100.200 // %.3f, putting 3 decimal places always •100 // %.3g, putting 3 significant figures •3.142 // %.3f, putting 3 decimal places again•3.14 // %.3g, putting 3 significant figures For integers, on the other hand, the precision it controls the minimum number of digits printed:printf( "%.3d", 10 ); Will print the number 10 with three digits: 010

Page 37: 6 operators-in-c

37

Precision (cont…)Finally, for strings, the precision controls the maximum length of the string displayed:

printf( "%.5s\n", "abcdefg" ); displays only "abcde“

Width:The width field is almost the opposite of the precision field. Precision controls the max number of characters to print, width controls the minimum number, and has the same format as precision, except without a decimal point:printf( "%5s\n", "abc" ); //prints abc ;two blank spaces go at the beginning, by default.

You can combine the precision and width, if you like: <width>.<precision>printf( "%8.5f\n", 1.234 ); prints 1.23400.

Page 38: 6 operators-in-c

FlagThe flag setting controls 'characters' that are added to a string, such whether to append 0x to a hexadecimal number, or whether to pad numbers with 0s.The specific flag options are•The Pound Sign: #•Adding a # will cause a '0' to be prepended to an octal number (when using the o conversion specifier), or a 0x to be prepended to a hexadecimal number (when using a x conversion specifier). •printf( "%#x", 12 ); // prints in 0xc •Whereas printf( "%x", 12 ); //prints c•The Zero Flag: 0•Using 0 will force the number to be padded with 0s. This only really matters if you use the width setting to ask for a minimal width for your number. For example, if you write:•printf( "%05d\n", 22 ); //prints 00022•The Plus Sign Flag: +•The plus sign will include the sign specifier for the number:•printf( "%+d\n", 10 ); //Will print +10

Page 39: 6 operators-in-c

Example

Characters: a ADecimals: 1977 650000Preceding with blanks: 1977Preceding with zeros: 0000001977Some different radixes: 100 64 144 0x64 0144Width trick: 10A string

#include <stdio.h>int main( ){ printf ("Characters: %c %c \n", 'a', 65); printf ("Decimals: %d %ld\n", 1977, 650000); printf ("Preceding with blanks: %10d \n", 1977); printf ("Preceding with zeros: %010d \n", 1977); printf ("Some different radixes: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("Width trick: %*d \n", 5, 10); printf ("%s \n", "A string"); return 0; }

Page 40: 6 operators-in-c

scanf( ):scanf( ) statement is used to read data from standard input stream (stdin), the keyboard. The syntax is:scanf( format string with specifiers, variable names)The specifier list is same as that of printf( ).Example:void(){

char x;int y,n;float z;n=scanf(“%c%d%f”, &x, &y, &z);

printf(“Returned value of scanf is =%d”,n); }scanf( ) returns the number of values successfully read.

Page 41: 6 operators-in-c

Example/* Calculation of simple interest */main( ){int p, n ;float r, si ;printf ( "Enter values of p, n, r" ) ;scanf ( "%d %d %f", &p, &n, &r ) ;si = p * n * r / 100 ;printf ( “Simple Interest=%f" , si ) ;} Note that the ampersand (&) before the variables in the scanf( )function

is a must. & is an ‘Address of’ operator. It gives the location number used by the variable in memory. When we say &a, we are telling scanf( ) at which emory location should it store the value supplied by the user from the keyboard.

41

Page 42: 6 operators-in-c

Example// PROGRAM 1#include<stdio.h> int main(void){    int a = 1, 2, 3;    printf("%d", a);    return 0;}

42

// PROGRAM 2#include<stdio.h> int main(void){    int a;    a = 1, 2, 3;    printf("%d", a);    return 0;}

// PROGRAM 3#include<stdio.h> int main(void){    int a;    a = (1, 2, 3);    printf("%d", a);    return 0;}

Page 43: 6 operators-in-c

Escape sequences

43

Escape sequence Description \' Output the single quote (') character. \" Output the double quote (") character. \? Output the question mark (?) character. \\ Output the backslash (\) character. \a Cause an audible (bell) or visual alert. \b Move the cursor back one position on the current line. \f Move the cursor to the start of the next logical page. \n Move the cursor to the beginning of the next line. \r Move the cursor to the beginning of the current line. \t Move the cursor to the next horizontal tab position. \v Move the cursor to the next vertical tab position.

Page 44: 6 operators-in-c

Example#include <stdio.h>   int main() { printf(“This\n is\n a\n test\n \n He said, \“

How are you?\ "\n”); }OutputThis is a test   He said, "How are you?"

44

Page 45: 6 operators-in-c

ASCII( American Standard Code for Information Interchange) Values

45

Page 46: 6 operators-in-c

Example#include<stdio.h> void main(){

char ch='a'; printf("ASCII value of %c is =

%d",ch,ch); }

Will print:ASCII value of a is =97

46

Page 47: 6 operators-in-c

47

Type Conversions

Implicit Type Conversion:The operands of a binary operator must have the same type and the result is also of the same type.Integer division:

c = 9 / 2 -- c=4 (logically wrong)Here the operands of the division are both int and hence the result also would be int. For correct results, one may write

c = 9.0 / 2 -- c=4.5In case the two operands of a binary operator are different, then the ‘lower’ type will be converted to the ‘higher’ type by the compiler. This mechanism is called Type Conversion(Implicit Type Conversion).int i=4 ,x;float f=2.5;double d=10.5;x=i*f+d; // x will have

20

Page 48: 6 operators-in-c

Type Conversion for assignment

Values can be converted by assigning one expression into the other. There are two types:o widening conversiono narrowing conversion

char short int long float double long doubleAssignment in forward direction is widening conversion; no data is

lost in it. Assignment in backward direction is called narrowing conversion;

data loss is possible in this case.char a = 10;int b, c;float d = 2.6;b = a; // widening conversion, no data lossc = d; // narrowing conversion, data loss, c gets value only 2

Page 49: 6 operators-in-c

Example of narrowing conversion

49

Page 50: 6 operators-in-c

Explicit conversion (Type Casting): Type casting is used to convert the data type of an identifier to another data type temporarily.

#inlcude <stdio.h>int main( ) {int a=11, b=2;float c;c = (float)a / b;printf(“\n%f”, c);return 0;}

Page 51: 6 operators-in-c

Which option is correct?Main(){int x=2;printf(“%d %d”,++x,++x);}a.3 4b. 4 3c. 4 4d. o/p may vary from complier to complier

51

d. o/p may vary from complier to complier

Page 52: 6 operators-in-c

Which option is correct?Main(){ int x=10,y=20,z=5,a a=x<y<z; printf(“%d”,a);}a. 1b. 0c .errord. none of above.

52a.

Page 53: 6 operators-in-c

Which option is correct?Main(){ printf(“\nHey JUET”); printf(“\b\b\b\bMP”); printf(“\rHii”);}a. Hey JUETb. Hii MPc .errord. Hey MP

53Ans: b. Hii MP