1 / 53

OPERATORS IN C

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) Arithmetic 2) Assignment 3) Logical/Relational 4) Bitwise 5) Odds and ends. Arithmetic Operators.

rgreen
Download Presentation

OPERATORS IN C

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OPERATORS IN C

  2. 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) Arithmetic • 2) Assignment • 3) Logical/Relational • 4) Bitwise • 5) Odds and ends

  3. Arithmetic Operators Pre increment/Decrement (++i or --i): First increment/decrement current value by 1 and then use the incremented/decremented value Post increment/Decrement (i++ or i--): First use the current value and then increment/decrement current value by 1 for next time use

  4. 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); 2 printf(“%d %d \n”,i++,++j); 7 6 }

  5. 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 lvalue Example: i=i+1 can also be reduced to i+=1

  6. Assignment Operators Example

  7. Relational Operators a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities.  • If condition is true it returns 1 else returns 0.

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

  9. 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; }

  10. 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.

  11. &&(Logical AND) • The && operator is used to determine whether both operands or conditions are true • For 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 !”);

  12. Example of Logical operator Output:

  13. || (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.

  14. ! (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 !”);

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

  16. Bitwise AND • 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)

  17. Bitwise OR(|) • 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

  18. 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 times • int b=4>>1 • printf(“%d”,b);// •  Right shifting 1 time, is equivalent to dividing the value by 2. will print 4 will print 2

  19. Bitwise Operators Example

  20. Odds and Ends Operators • There are few other important operators including sizeof and ? : supported by C Language.

  21. 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) ); }

  22. 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 ); }

  23. Operators available in C can be classified in following way: unary – that requires only one operand. For example: &a, ++a, *a ,--b etc. binary - that requires two operands. For example: a + b, a * b, a<<2 ternary - that requires three operands. For example: (a>b) ? a : b [ ? : ]

  24. Precedence and associativity • 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. • Associativity indicates in which order two operators of same precedence (priority) executes.

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

  26. Example of Associativity of Operators 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 Ex2 Associativity is important, since it changes the meaning of an expression. Consider the division operator with integer arithmetic, which is left associative 4 / 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 zero 4 / 2 / 3  4 / (2 / 3)  4 / 0 = undefined

  27. What will be the value of i 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: +

  28. Arithmetic expressions vs C expressions • Although Arithmetic instructions look simple to use one often commits mistakes in writing them. • following points should keep in mind while writing C programs: • 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.

  29. Arithmetic expressions vs C expressions(cont..) (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 statement b = 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.

  30. Arithmetic expressions vs C expressions(cont..)

  31. Examples Based on Operators 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=5 4 c=0

  32. Comma Operator • 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.

  33. 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

  34. 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

  35. 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.

  36. Flag • The 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

  37. Example #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; } Characters: a A Decimals: 1977 650000 Preceding with blanks: 1977 Preceding with zeros: 0000001977 Some different radixes: 100 64 144 0x64 0144 Width trick: 10 A string

  38. 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.

  39. 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.

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

  41. Escape sequences

  42. Example #include <stdio.h>   int main() { printf(“This\n is\n a\n test\n \n He said, \“ How are you?\ "\n”); } Output This is a test   He said, "How are you?"

  43. ASCII( American Standard Code for Information Interchange) Values

  44. 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

  45. 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.5 • In 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

  46. Type Conversion for assignment • Values can be converted by assigning one expression into the other. There are two types: • widening conversion • narrowing conversion char short  int  long float  double long double Assignment 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 loss c = d; // narrowing conversion, data loss, c gets value only 2

  47. Example of narrowing conversion

  48. 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; }

More Related