Operators & Expressions important in C program



Operators

Ø  C Operators are symbols that represent operations to be performed on one or more operands.

Ø  C provides a wide range of operators, which can be classified into different categories based on their functionality.

Ø  Operators are used for performing operations on variables and values.

Ø  Operators can be defined as the symbols that help us to perform specific mathematical, relational, bitwise, conditional, or logical computations on operands.

Ø  For example, ‘+’ is an operator used for addition.

Types Operators in C


Arithmetic Operator

Ø  An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).



             #include <stdio.h>

            int main(){

                int a = 9,b = 4, c;

                c = a+b;

                printf("a+b = %d \n",c);

                c = a-b;

                printf("a-b = %d \n",c);

            c = a*b;

                printf("a*b = %d \n",c);

                c = a/b;

                printf("a/b = %d \n",c);

                c = a%b;

                printf("Remainder when a divided by b = %d \n",c);   

                return 0;

            }

Relational Operator

Ø  A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.

Ø  Relational operators are used in decision making and loops.


            #include <stdio.h>

            int main()

            {

                int a = 5, b = 5, c = 10;

                

                printf("%d == %d is %d \n", a, b, a == b);

                printf("%d == %d is %d \n", a, c, a == c);

                printf("%d > %d is %d \n", a, b, a > b);

                printf("%d > %d is %d \n", a, c, a > c);

                printf("%d < %d is %d \n", a, b, a < b);

                printf("%d < %d is %d \n", a, c, a < c);

            printf("%d != %d is %d \n", a, b, a != b);

                printf("%d != %d is %d \n", a, c, a != c);

                printf("%d >= %d is %d \n", a, b, a >= b);

                printf("%d >= %d is %d \n", a, c, a >= c);

                printf("%d <= %d is %d \n", a, b, a <= b);

                printf("%d <= %d is %d \n", a, c, a <= c);

                return 0;

            }

Logical Operator

Ø  An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false.

Ø  Logical operators are commonly used in decision making in C programming.


            #include <stdio.h>

            int main()

            {

                int a = 5, b = 5, c = 10, result;

                result = (a == b) && (c > b);

                printf("(a == b) && (c > b) is %d \n", result);

                result = (a == b) && (c < b);

                printf("(a == b) && (c < b) is %d \n", result);

                result = (a == b) || (c < b);

                printf("(a == b) || (c < b) is %d \n", result);

                result = (a != b) || (c < b);

                printf("(a != b) || (c < b) is %d \n", result);

                result = !(a != b);

                printf("!(a != b) is %d \n", result);

                result = !(a == b);

                printf("!(a == b) is %d \n", result);

                return 0;

            }

Assignment Operator

Ø  An assignment operator is used for assigning a value to a variable.

Ø  The most common assignment operator is =

 


 

            #include <stdio.h>

            int main()

            {

                int a = 5, c;

                c = a;      // c is 5

                printf("c = %d\n", c);

                c += a;     // c is 10

                printf("c = %d\n", c);

                c -= a;     // c is 5

                printf("c = %d\n", c);

                c *= a;     // c is 25

                printf("c = %d\n", c);

                c /= a;     // c is 5

                printf("c = %d\n", c);

                c %= a;     // c = 0

                printf("c = %d\n", c);

                return 0;

            }

Increment/decrement Operator

Ø  C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.

Ø  Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.

Ø  These two operators are unary operators, meaning they only operate on a single operand.

             #include <stdio.h>

            int main()

            {

                int a = 10, b = 100;

                float c = 10.5, d = 100.5;

                printf("++a = %d \n", ++a);

                printf("--b = %d \n", --b);

                printf("++c = %f \n", ++c);

                printf("--d = %f \n", --d);

                return 0;

            }

Increment/decrement operator as prefix and postfix

Ø  If you use the ++ operator as a prefix like: ++var, the value of var is incremented by 1; then it returns the value.

Ø  If you use the ++ operator as a postfix like: var++, the original value of var is returned first; then var is incremented by 1.

Ø  The -- operator works in a similar way to the ++ operator except -- decreases the value by 1.

Increment/decrement Operator-Example

            #include <stdio.h>

            int main() {

               int var1 = 5, var2 = 5;

               // 5 is displayed

               // Then, var1 is increased to 6.

               printf("%d\n", var1++);

               // var2 is increased to 6

               // Then, it is displayed.

               printf("%d\n", ++var2);

               return 0;

            }

            Conditional Operator

The conditional operator is also known as a ternary operator.The conditional statements are the decision-making statements which depends upon the output of the expression.It is represented by two symbols, i.e., '?' and ':' As conditional operator works on three operands, so it is also known as the ternary operator.

            The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.

            Syntax of a conditional operator

            Expression1? expression2: expression3;  

            Conditional Operator-Syntax


Ø  In the above syntax, the expression1 is a Boolean condition that can be either true or false value.

Ø  If the expression1 results into a true value, then the expression2 will execute.

Ø  The expression2 is said to be true only when it returns a non-zero value.

Ø  If the expression1 returns false value then the expression3 will execute.

Ø  The expression3 is said to be false only when it returns zero value.

Conditional Operator-Example

            #include <stdio.h>  

            int main()  

           

                int age = 20;  // variable declaration  

               (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));  // conditional operator  

                return 0;  

            }  

Bitwise Operator

Ø  In the arithmetic-logic unit (which is within the CPU), mathematical operations like: addition, subtraction, multiplication and division are done in bit-level.

Ø  To perform bit-level operations in C programming, bitwise operators are used.

Operator

Meaning of operators

&

Bitwise AND

|

Bitwise OR

^

Bitwise exclusive OR

~

Bitwise complement

<< 

Shift left

>> 

Shift right

 

 Bitwise AND Operator (&)

Ø  The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.

Ø  In C Programming, the bitwise AND operator is denoted by &.

Ø  Let us suppose the bitwise AND operation of two integers 12 and 25.

Ø  12 = 00001100 (In Binary)

Ø  25 = 00011001 (In Binary)

Ø  Bit Operation of 12 and 25

Ø      00001100

Ø  & 00011001

Ø    ________

Ø      00001000  = 8 (In decimal)

  #include <stdio.h>

  int main() {

      int a = 12, b = 25;

      printf("Output = %d", a & b);

      return 0;

  }

Bitwise OR Operator (|)

Ø  The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1.

Ø  In C Programming, bitwise OR operator is denoted by |.

Ø  12 = 00001100 (In Binary)

Ø  25 = 00011001 (In Binary)

Ø  Bitwise OR Operation of 12 and 25

Ø     00001100

Ø  | 00011001

Ø    ________

Ø    00011101  = 29 (In decimal)

  #include <stdio.h>

  int main() {

      int a = 12, b = 25;

      printf("Output = %d", a | b);

      return 0;

  }

Bitwise XOR (exclusive OR) Operator (^)

Ø  The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^.

Ø  12 = 00001100 (In Binary)

Ø  25 = 00011001 (In Binary)

Ø  Bitwise XOR Operation of 12 and 25

Ø     00001100

Ø  ^ 00011001

Ø    ________

Ø     00010101  = 21 (In decimal)

  #include <stdio.h>

  int main() {

      int a = 12, b = 25;

      printf("Output = %d", a ^ b);

      return 0;

  }

Bitwise Complement Operator (~)

Ø  Bitwise complement operator is a unary operator (works on only one operand).

Ø  It changes 1 to 0 and 0 to 1. It is denoted by ~.

Ø  For any integer n, bitwise complement of n will be -(n + 1).

Ø  To understand this, you should have the knowledge of 2's complement.

  #include <stdio.h>

  int main() {

      printf("Output = %d\n", ~35);

      printf("Output = %d\n", ~-12);

      return 0;

  }

Bitwise Shift Left Operator (<<)

Ø  Left shift operator shifts all bits towards left by a certain number of specified bits.

Ø  The bit positions that have been vacated by the left shift operator are filled with 0.

Ø  The symbol of the left shift operator is <<.

Ø  212 = 11010100 (In binary)

Ø  212<<1 = 110101000 (In binary) [Left shift by one bit]

Ø  212<<0 = 11010100 (Shift by 0)

Ø  212<<4 = 110101000000 (In binary) =3392(In decimal)

Bitwise Shift Right Operator (>>)

Ø  Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by  >>.

Ø  212 = 11010100 (In binary)

Ø  212 >> 2 = 00110101 (In binary) [Right shift by two bits]

Ø  212 >> 7 = 00000001 (In binary)

Ø  212 >> 8 = 00000000

Ø  212 >> 0 = 11010100 (No Shift)

Bitwise Shift Operator-Example

            #include <stdio.h>

            int main() {

                int num=212, i;

                for (i = 0; i <= 2; ++i) {

                    printf("Right shift by %d: %d\n", i, num >> i);

                }

                printf("\n");

                for (i = 0; i <= 2; ++i) {

                    printf("Left shift by %d: %d\n", i, num << i);   

                }

                return 0;

            }

Comma Operator

Ø  The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

Ø  The comma sign is used for mainly two different purposes in the C language –

Ø  as an operator and

Ø  as a separator.

Ø  Thus, its behavior is very different according to where we place/use it in a program.

Ø  The Comma as a Separator

Ø  When we want to declare multiple numbers of variables in any program and provide different arguments in any function, we use the comma in the form of a separator in the program.

Ø  For instance,

Ø  int x, y, z;

Ø  The Comma as an Operator

Ø  We use the comma in the form of an operator when we want to assign multiple numbers of values to any variable in a program with the help of a comma.

Ø  For instance,

Ø  p = 40, 50, 60, 70, 80, 90;

Ø  q = (40, 50, 60, 70, 80, 90);

Size of Operator

Ø  We mainly use the Sizeof() Operator in C for giving the total amount of storage required (in bytes), for storing any object in the form of an operand.

Ø  The sizeof() operator allows a user to avoid the specification of the machine-dependent type of data sizes in any program.

Ø  We generally use the sizeof() operator in the C language so that we can determine the sizes of the data types or the expressions that are specified in the storage units.

Operator Precedence and Associativity

Ø  The precedence of operators in C dictates the order in which the operators will be evolved in an expression.

Ø  Associativity, on the other hand, defines the order in which the operators of the same precedence will be evaluated in an expression.

Ø  Also, associativity can occur from either right to left or left to right.

Precedence   

   Operator   
 

Description

   Associativity   

1

()

Parentheses (function call)

Left-to-Right

[]

Array Subscript (Square Brackets)

.

Dot Operator

->

Structure Pointer Operator

++ , —

Postfix increment, decrement

 

2

++ / —

Prefix increment, decrement

Right-to-Left

+ / –

Unary plus, minus

! , ~

Logical NOT,  Bitwise complement

(type)

Cast Operator

*

Dereference Operator

&

Address of Operator

size of

Determine size in bytes

 

3

*,/,%

Multiplication, division, modulus

Left-to-Right

4

+/-

Addition, subtraction

Left-to-Right

5

<< , >>

Bitwise shift left, Bitwise shift right

Left-to-Right

6

< , <=

Relational less than, less than or equal to

Left-to-Right

> , >=

Relational greater than, greater than or equal to

 

7

== , !=

Relational is equal to, is not equal to

Left-to-Right

8

&

Bitwise AND

Left-to-Right

9

^

Bitwise exclusive OR

Left-to-Right

10

|

Bitwise inclusive OR

Left-to-Right

11

&&

Logical AND

Left-to-Right

12

||

Logical OR

Left-to-Right

13

?:

Ternary conditional

Right-to-Left

 

14

=

Assignment

Right-to-Left

+= , -=

Addition, subtraction assignment

*= , /=

Multiplication, division assignment

%= , &=

Modulus, bitwise AND assignment

^= , |=

Bitwise exclusive, inclusive OR assignment

<<=, >>=

Bitwise shift left, right assignment

15

,

comma (expression separator)

Left-to-Right

 Expressions

Ø  An expression is a formula in which operands are linked to each other by the use of operators to compute a value.

Ø  An operand can be a function reference, a variable, an array element or a constant.

Ø  Example: a+b-c

Ø  Here, a,b & c is operand, + and  - is operator.

Ø  Types of Expressions

Ø  Arithmetic expressions

Ø  Relational expressions

Ø  Logical expressions

Ø  Conditional expressions


Arithmetic Expressions

Ø  An arithmetic expression is an expression that consists of operands and arithmetic operators.

Ø  An arithmetic expression computes a value of type int, float or double.

Ø  When an expression contains only integral operands, then it is known as pure integer expression when it contains only real operands, it is known as pure real expression, and when it contains both integral and real operands, it is known as mixed mode expression.

Ø  The expressions are evaluated by performing one operation at a time.

Ø  The precedence and associativity of operators decide the order of the evaluation of individual operations.

Evaluation of Arithmetic Expressions

Ø  When both the operands are of type integer, then arithmetic will be performed, and the result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.

Ø  When both the operands are of type float, then arithmetic will be performed, and the result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.

Ø  If one operand is of type integer and another operand is of type real, then the mixed arithmetic will be performed. In this case, the first operand is converted into a real operand, and then arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.

Ø  Example:

Ø  6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Ø  6*2/(2+2/3 + 6) + 8 * (8/4)

Ø  6*2/(2+0+6) + 8 * (8/4)

Ø  6*2/ 8+ 8 * (8/4)

Ø  6*2/8 + 8 * 2

Ø  12/8 +8 * 2

Ø  1 + 8 * 2

Ø  1 + 16

Ø  17

Relational expressions

Ø  A relational expression is an expression used to compare two operands.

Ø  It is a condition which is used to decide whether the action should be taken or not.

Ø  In relational expressions, a numeric value cannot be compared with the string value.

Ø  The result of the relational expression can be either zero or non-zero value. Here, the zero value is equivalent to a false, and non-zero value is equivalent to a true.

Relational Expression

Description

x%2 = = 0

This condition is used to check whether the x is an even number or not. The relational expression results in value 1 if x is an even number otherwise results in value 0.

a!=b

It is used to check whether a is not equal to b. This relational expression results in 1 if a is not equal to b otherwise 0.

a+b = = x+y

It is used to check whether the expression "a+b" is equal to the expression "x+y".

a>=9

It is used to check whether the value of a is greater than or equal to 9.

 Relational expressions-Example

            #include <stdio.h>  

             int main()  

            {        

                int x=4;  

                if(x%2==0)  

                {  

                    printf("The number x is even");  

                }  

                else  

                printf("The number x is not even");  

                return 0;  

            }  

Logical expressions

Ø  A logical expression is an expression that computes either a zero or non-zero value.

Ø  It is a complex test condition to take a decision.

Logical Expressions

Description

( x > 4 ) && ( x < 6 )

It is a test condition to check whether the x is greater than 4 and x is less than 6. The result of the condition is true only when both the conditions are true.

x > 10 || y <11

It is a test condition used to check whether x is greater than 10 or y is less than 11. The result of the test condition is true if either of the conditions holds true value.

! ( x > 10 ) && ( y = = 2 )

It is a test condition used to check whether x is not greater than 10 and y is equal to 2. The result of the condition is true if both the conditions are true.

 Logical expressions-Example

            #include <stdio.h>  

            int main()  

            {  

                int x = 4;  

                int y = 10;  

                if ( (x <10) && (y>5))  

                {  

                    printf("Condition is true");  

                }  

                else  

                printf("Condition is false");  

                return 0;  

            }  

Conditional expressions

Ø  A conditional expression is an expression that returns 1 if the condition is true otherwise 0.

Ø  A conditional operator is also known as a ternary operator.

Ø  The Syntax of Conditional operator

Ø  Suppose exp1, exp2 and exp3 are three expressions.

Ø  exp1 ? exp2 : exp3

Ø  The above expression is a conditional expression which is evaluated on the basis of the value of the exp1 expression.

Ø  If the condition of the expression exp1 holds true, then the final conditional expression is represented by exp2 otherwise represented by exp3.

Conditional expressions-Example

            #include<stdio.h> 

            int main() 

           

                int age = 25; 

                char status; 

                status = (age>22) ? 'M': 'U'; 

                if(status == 'M') 

                printf("Married"); 

                else 

                printf("Unmarried"); 

                return 0; 

            }

Type Casting in Expression

Ø  Type Casting is basically a process in C in which we change a variable belonging to one data type to another one.

Ø  In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

Ø  For instance, in case we assign a float variable (floating point) with an integer (int) value, the compiler will ultimately convert this int value into the float value.

Ø  The process of casting allows the programmers to make such types of conversions explicit or even force it in cases where it wouldn’t happen normally.

Ø  Types of Type Casting in C

Ø  Implicit

Ø  Explicit

Implicit Type Casting

Ø  Implementing the implicit type casting is very easy in a program. We use it to convert the data type of any variable without losing the actual meaning that it holds. The implicit type casting occurs automatically.

Ø  In simpler words, the implicit type casting performs the conversion without altering any of the values stored in the program’s variables.

Ø  Follow these points to understand what rules the implicit type casting follows in a C program:

Ø  If we are performing a conversion on two of the different data types in a program, then the conversion of the lower data type to the higher data type will occur automatically.

Ø  If we suppose that we are performing the type casting operation among two different data types like float and int, then the resultant value would be the floating data type (float).

Examples of Implicit Type Casting in C

            int x = 4;

            float a = 12.4, b;

            b = a / x;

Ø  In the example given above, the variable x will get converted to the float data type (float) automatically, and it is comparatively a bigger data type in C.

Ø  Here, the variable x and the variable a would be equal in terms of their data types.

Ø  Thus, the value of b would be equal to 12.4/4.0=3.1.

Explicit Type Casting

Ø  Conversely, in the case of explicit typecasting, the programmer needs to force the conversion.

Ø  In simpler words, one has to perform typecasting on the data types on their own.

Ø  Syntax:

Ø  (name_of_data_type) expression

Ø  Here, name_of_data_type refers to the name of that data type to which we want to convert the available data type in the code. This expression can be a constant, a variable, or even an actual expression in a program.

Examples of Explicit Type Casting in C

            float num = 56.3;

            int p = (int)num + 50; // data type casting explicitly

            printf(“The value of the variable p is: %d\n”,p);

Ø  In the example mentioned above, we perform the declaration of a variable of a float type, named num.

Ø  After this, the float variable gets converted into an int (integer) data type with the help of explicit data type casting.

Ø  After this, it gets added with the number 50, and we get an output of an integer.

Usual Arithmetic Conversion


Program Statement

Ø  A statement forms a complete unit of execution and is terminated with a semicolon ( ; ).

Ø  C statements consist of tokens, expressions, and other statements.

Ø  A statement that forms a component of another statement is called the "body" of the enclosing statement.

Ø  There are three kinds of statements: 

Ø  expression statements,

Ø Declaration statements, and

Ø  control flow statements.

 

 

 

 

 

 

 

 

No comments:

Post a Comment

Research in Social Science

   C  Concept of Research in Social Science -         Understanding the concept of Research Methods, Techniques and Tools: Interview, Fo...