AsegGasiaBlog

C Programming - Operators

Operators 

Arithmetic Operators
  • Arithmetic operators are used for Arithmetic Calculation.
  • These are used to perform mathematical calculations like addition (+), subtraction(-), multiplication (*), division (/), and modulus (remainder) (%).

Example :


#include<stdio.h>

int main()
{
    int num1,num2;
    int add,subs,mul,div,mod;

    printf("\nEnter First Number :");
    scanf("%d",&num1);

    printf("\nEnter Second Number :");
    scanf("%d",&num2);

    // (+) operator
    add = num1 + num2;
    printf("\nAddition is : %d",add);

    // (-) operator
    subs = num1 - num2;
    printf("\nSubtraction is : %d",subs);

    // (*) operator
    mul = num1 * num2;
    printf("\nMultiplication is : %d",mul);

    // (÷) operator
    div = num1 / num2;
    printf("\nDivision is : %d",div);

    // (%) operator
    mod = num2 % num1;
    printf("\nModulus is : %d",mod);

    return(0);
}

Output

    Enter First Number : 10
    Enter Second Number : 2
    Addition is : 12
    Subtraction is : 8
    Multiplication is : 20
    Division is : 5
    Modulus is : 2

Assigment Operator
  • Assignment operator is used to assign value to an variable.
  • Example : a = b. Assigns values from right side operands to left side operand.
  • Assignment operator is binary operator which operates on two operands (variable).

Example :


int main()
{
    int a;

    // variable a is assigned integer value 55
    a = 55;

    return (0);

}

Relational operators

Relational operators are used to compare the value of two variables.

Operators

OperatorUse
==Check value of 2 variable are equal
!=Check value of 2 variable are equal or not
>check is value is greater than
>=check is value is greater than or equal to
<check value is less than
<=check value is less than or equal to

Example :


#include <stdio.h>

int main()
{
    int a = 21;
    int b = 10;
    int c ;

    // == operator
    if( a == b )
    {
        printf("a is equal to b\n" );
    }
    else
    {
        printf("a is not equal to b\n" );
    }

    // < operator
    if ( a < b )
    {
        printf("a is less than b\n" );
    }
    else
    {
        printf("a is not less than b\n" );
    }

    // > operator
    if ( a > b )
    {
        printf("a is greater than b\n" );
    }
    else
    {
        printf("a is not greater than b\n" );
    }

    // Lets change value of a and b
    a = 5;
    b = 20;
    // <= operator
    if ( a <= b )
    {
    printf("a is either less than or equal to  b\n" );
    }


    // >= operator
    if ( b >= a )
    {
        printf("b is either greater than  or equal to b\n" );
    }

    return 0;
}

Output :

    a is not equal to b
    a is not less than b
    a is greater than b
    a is either less than or equal to  b
    b is either greater than  or equal to b

Logical Operators

Logical operators are used to perform logical operations on the given two variables.

Logical operators :

OperatorUsage
&&expr1 && expr2
||expr1 || expr2
!!expr1

Logical operator chart :

OperatorCondition 1Condition 2Result
&&TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
||TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
!True-False
False-True

Example :


a = 5;
b = 10;

(a == 5) && (b < 5) = false
/*
    here, first expression a == 5 is true
          second expression b < 5 is false
    so, final result of && operator is false
    (True && False = False)
*/

(a == 4) && (b < 15) = false
(a == 5) && (b < 15) = true
(a == 4) && (b < 5) = false

(a == 5) || (b < 5) = true
(a == 4) || (b < 15) = true
(a == 4) || (b < 5) = false

!(a == 5) = false
!(a == 4) = true

Increment And Decrement Operator

  • Increment operator (++) increases the value of its operand by 1
  • Decrement operator (--) decreases the value of its operand by 1

Example :


int  x;
int  y;

// Increment operators
x = 1;

y = ++x;    // x is now 2, y is also 2
y = x++;    // x is now 3, y is 2

// Decrement operators
x = 3;
y = x--;    // x is now 2, y is 3
y = --x;    // x is now 1, y is also 1

Bitwise Operators

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

Syntax :


    (condition) ? expression1 : expression2

If condition is true expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression.

Example :


#include <stdio.h>

int main()
{
    int a = 5;
    char c;

    //Example 1
    // condition ? expression1 : expression2
    c = (a < 10) ? 'S' : 'L';
    printf("C = %c",c);

    //Example 2
    // condition ? ( condition ? expression1 : expression2 ) : expression2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
    printf("\nC = %c",c);

    return 0;
}

Output :

    C = S
    C = l

Explanation :

//Example 1
    c = (a < 10) ? 'S' : 'L';

This means, if (a < 10), then c = S else c = L

//Example 2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');

This means, if (a < 10), then check one more conditions if(a < 5), then c = s else l, else c = L.

operators perform manipulations of data at bit level. These operators also perform shifting of bits from right to left. Bitwise operators are not applied to float or double.

OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise XOR
<<Left shift
>>Right shift

Explanation :


& (Bitwise AND) - The Bitwise AND will take pair of bits from each position, and if only both the bit is 1, the result on that position will be 1. Bitwise AND is used to Turn-Off bits.


    int a = 10;
    int b = 12;
    int c = a & b;

Calculation :

            bit
    a =    1010
    b =  & 1100
       ----------
    c =    1000
       ----------
    value of c = 8;

| (Bitwise OR) - The Bitwise OR, will take pair of bits from each position, and if any one of the bit is 1, the result on that position will be 1 else 0.


    int a = 10;
    int b = 12;
    int c = a | b;

Calculation :

            bit
    a =    1010
    b =  | 1100
       ----------
    c =    1110
       ----------
    value of c = 14;

^ (Bitwise XOR) - The Bitwise XOR will take pair of bits from each position, and if both the bits are different, the result on that position will be 1. If both bits are same, then the result on that position is 0.


    int a = 10;
    int b = 12;
    int c = a ^ b;

Calculation :

            bit
    a =    1010
    b =  ^ 1100
       ----------
    c =    0110
       ----------
    value of c = 6;

<< (Left shift) - Left shift operator will shift the bits towards left for the given number of times.


    int a = 6;
    int b = a << 2;

Calculation :

    a = 6
    Position 7 6 5 4 3 2 1
    6 in bit 0 0 0 0 1 1 0
    Shifting 2 bit to left
    Position 7 6 5 4 3 2 1
    Result   0 0 1 1 0 0 0
    value of b = 24;

>> (Right shift) - Right shift operator will shift the bits towards right for the given number of times.


    int a = 6;
    int b = a >> 2;

Calculation :

    a = 6
    Position 7 6 5 4 3 2 1
    6 in bit 0 0 0 0 1 1 0
    Shifting 2 bit to right
    Position 7 6 5 4 3 2 1
    Result   0 0 0 0 0 0 1
    value of b = 1;

Ternary Oprators

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

Syntax :


    (condition) ? expression1 : expression2

If condition is true expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression.

Example :


#include <stdio.h>

int main()
{
    int a = 5;
    char c;

    //Example 1
    // condition ? expression1 : expression2
    c = (a < 10) ? 'S' : 'L';
    printf("C = %c",c);

    //Example 2
    // condition ? ( condition ? expression1 : expression2 ) : expression2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
    printf("\nC = %c",c);

    return 0;
}

Output :

    C = S
    C = l

Explanation :

//Example 1
    c = (a < 10) ? 'S' : 'L';

This means, if (a < 10), then c = S else c = L

//Example 2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');

This means, if (a < 10), then check one more conditions if(a < 5), then c = s else l, else c = L.


Comma Operator

The comma operator has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.

  • The comma operator is mainly useful for obfuscation.
  • The comma operator allows grouping expression where one is expected.
  • Commas can be used as separators in some contexts, such as function argument lists.

Example :


#include <stdio.h>
int main ()
{
    int i = 10, b = 20, c= 30;

    // here, we are using comma as separator
    i = b, c;

    printf("%i\n", i);

    // bracket makes its one expression.
    // all expression in brackets will evaluate but
    // i will be assigned with right expression (left-to-right associativity)
    i = (b, c);
    printf("%i\n", i);

    return 0;
}

Output :

    20
    30

Type Cast Operator

Cast operator can be used to explicitly convert the value of an expression to a different data type

Two Types of Cast

  • Implicit Cast
  • Explicit cast
Implicit Cast -

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.

Explicit Cast -

Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion).

  • Lower DataType to Higher DataType are converted implicitly
  • Higher DataType to Lower DataType are converted explicitly

Example :


#include <stdio.h>

int main()
{
    int i   = 10;
    float f = 3.147;

    printf("The integer is: %d\n", i);
    printf("The float is:   %f\n", f);

    //implicit conversion
    f = i;
    printf("Implicit conversion int to float :   %f\n", f);

    //explicit conversion
    i = (int) f;
    printf("Explicit conversion float to int :   %d\n", i);

    return 0;
}

Output :

 The integer is: 10
 The float is:   3.147000
 Implicit conversion int to float :   10.000000
 Explicit conversion float to int :   10

Size Of Operator

C provides a compiler-time unary operator called sizeof that can be used to compute the size of any object.

The expression such as:

  • sizeof object
  • sizeof(type name)

Example :


#include<stdio.h>

int main()
{

    printf("size of int in byte :  %d\n", sizeof(int));
    printf("size of char in byte %d\n", sizeof(char));
    printf("size of float in byte %d", sizeof(float));

    return 0;
}

Output :

 size of int in byte :  4
 size of char in byte 1
 size of float in byte 4

C Shorthand

C has a special shorthand that simplifies coding of certain type of assignment.

For Example

a = a + 2;

can be written as :

a += 2;

Shorthand works for akk binary operators in C.

Syntax :

variable operator = variable / constant / expression

Operators are listed below :

OperatorsExampleMeaning
+=a+=2a=a+2
-=a-=2a=a-2
*=a*=2a=a*2
/=a/=2a=a/2
%=a%=2a=a%2
&&=a&&=2a=a&&2
||=a||=2a=a||2


Operator Precedence
Operator Associativity
() [] . -> expr++ expr-- left-to-right
* & + - ! ~ ++expr --expr (typecast) sizeofright-to-left
* / %left-to-right
+ -left-to-right
>> << left-to-right
< > <= >= left-to-right
== != left-to-right
& left-to-right
^ left-to-right
| left-to-right
&& left-to-right
|| left-to-right
?: right-to-left
= += -= *= /= %= >>= <<= &= ^= |= right-to-left
, left-to-right<

Order of Operation : PEMDAS

  • Parenthesis
  • Exponents
  • Multiplication
  • Division
  • Addition
  • Subtraction

Popular Posts