Unit 3
Operators and Expression in ‘C’
Every expression in C language contains set of operators and operands. Operators are the special symbols which are used to indicate the type of operation whereas operands are the data member or variables operating as per operation specified by operator. One expression contains one or more set of operators and operands. So to avoid the ambiguity in execution of expression, C compiler fixed the precedence of operator. Depending on the operation, operators are classified into following category.
- Arithmetic Operator: These are the operators which are useful in performing mathematical calculations. Following are the list of arithmetic operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
+ | Used to add two operands | Result of A+B is 15 | |
2. | - | Used to subtract two operands | Result of A-B is 5 |
3. | * | Used to multiply two operands | Result of A*B is 50 |
4. | / | Used to divide two operands | Result of A/B is 2 |
5. | % | Find reminder of the division of two operand | Result of A%B is 0 |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of addition of %d and %d is %d",a,b,a+b);
Printf("\n Result of subtraction of %d and %d is %d",a,b,a-b);
Printf("\n Result of multiplication %d and %d is %d",a,b,a*b);
Printf("\n Result of division of %d and %d is %d",a,b,a/b);
Printf("\n Result of modulus of %d and %d is %d",a,b,a%b);
Getch();
}
Output:
Enter two numbers
5
3
Result of addition of 5 and 3 is 8
Result of subtraction of 5 and 3 is 2
Result of multiplication of 5 and 3 is 15
Result of division of 5 and 3 is 1
Result of modulus of 5 and 3 is 2
2. Relational Operators: Relational operator used to compare two operands. Relational operator produce result in terms of binary values. It returns 1 when the result is true and 0 when result is false. Following are the list of relational operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
1. | < | This is less than operator which is used to check whether the value of left operand is less than the value of right operand or not | Result of A<B is false
|
2. | > | This is greater than operator which is used to check whether the value of left operand is greater than the value of right operand or not | Result of A>B is true |
3. | <= | This is less than or equal to operator | Result of A<=B is false |
4. | >= | This is greater than or equal to operator | Result of A>=B is true |
5. | == | This is equal to operator which is used to check value of both operands are equal or not | Result of A==B is false |
6. | != | This is not equal to operator which is used to check value of both operands are equal or not | Result of A!=B is true |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of less than operator of %d and %d is %d",a,b,a<b);
Printf("\n Result of greater than operator of %d and %d is %d",a,b,a>b);
Printf("\n Result of leass than or equal to operator %d and %d is %d",a,b,a<=b);
Printf("\n Result of greater than or equal to operator of %d and %d is %d", a,b,a>=b);
Printf("\n Result of double equal to operator of %d and %d is %d",a,b,a==b);
Printf("\n Result of not equal to operator of %d and %d is %d",a,b,a!=b);
Getch();
}
Output:
Enter two numbers
5
3
Result of less than operator of 5 and 3 is 0
Result of greater than operator of 5 and 3 is 1
Result of less than or equal to operator of 5 and 3 is 0
Result of greater than or equal to operator of 5 and 3 is 1
Result of double equal to operator of 5 and 3 is 0
Result of not equal to operator of 5 and 3 is 1
3. Logical Operators: Logical operators are used to compare logical values of two operands. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5.
Sr. No. | Operator | Description | Example |
1. | && | This is logical AND, it returns true when both the values are non zero | Result of (A&&B) is true |
2. | || | This is logical OR, it returns true when any of two value is non zero | Result of (A||B) is true |
3. | ! | This is logical NOT operator, it is used to reverse the logical state of operand | Result of !(A&&B) is false |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of logical and operator of %d and %d is %d",a,b,a&&b);
Printf("\n Result of logical or operator of %d and %d is %d",a,b,a||b);
Printf("\n Result of logical not operator of %d and and %d is %d",a,b,!(a&&b));
Getch();
}
Output:
Enter two numbers
5
3
Result of logical and operator of 5 and 3 is 1
Result of logical or operator of 5 and 3 is 1
Result of logical not operator of 5 and 3 is 0
4. Assignment Operators: Assignment operator is used to assign the value to variable. To understand the operation assume variable A contains value 10 and variable contains value 5.
Example: A=B;
In the above example value of variable B is assign to variable A. Result of this expression is value of A is 5 and value of B is 5.
5. Increments and Decrement Operators: These operator are used to increase or decrease the value of variable by one. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10.
Sr. No. | Operator | Description | Example |
1. | ++ | This is incremental operator which is used to increase the value of variable by 1 | Result of (A++) is value of A is 11 |
2. | -- | This is decremental operator which is used to decrease the value of variable by 1 | Result of (A--) is value of A is 9 |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a=5,b=5,c=5,d=5;
Clrscr();
Printf("Original value of a, b, c, d is %d \t %d \t %d \t %d",a,b,c,d);
a++;
Printf("\n New value of a is %d",a);
++b;
Printf("\n New value of b is %d",b);
Printf("\n New value of c is %d",c++);
Printf("\n New value of d is %d",++d);
Getch();
}
Output:
Original value of a, b, c, d is 5 5 5 5
New value of a is 6
New value of b is 6
New value of c is 5
New value of d is 6
6. Bitwise Operators: These operators are used to work on the each bits of data. These operators can work on the binary data. If the data is non binary then computer first of all convert it into binary form and then perform the operation. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5. So the binary values of
A = 0000 1010 and
B = 0000 0101
Sr. No. | Operator | Description | Example |
1. | & | This is bitwise AND | Result of (A&B) is 0000 0000 |
2. | | | This is bitwise OR | Result of (A|B) is 0000 1111 |
3. | ^ | This is bitwise Exclusive | Result of (A^B) is 0000 1111 |
4. | << | This is used to shift bit on left side | Result of (A<<B) is |
5. | >> | This is used to shift bit on right side | Result of (A>>B) is |
Example:
#include<stdio.h>
#include<conio.h>
Void main()
{
Int a,b,c;
Clrscr();
Printf("Enter two numbers");
Scanf("%d %d",&a,&b);
Printf("\n Result of bitwise and operator of %d and %d is %d",a,b,a&b);
Printf("\n Result of bitwise or operator of %d and %d is %d",a,b,a|b);
Printf("\n Result of bitwise exclusive operator of %d and %d is %d",a,b,a^b);
Printf("\n Result of bitwise left shift operator of %d and %d is %d",a,b,a<<b);
Printf("\n Result of bitwise right shift operator of %d and %d is %d",a,b,a>>b);
Getch();
}
Output:
Enter two numbers
5
3
Result of bitwise and operator of 5 and 3 is 1
Result of bitwise or operator of 5 and 3 is 7
Result of bitwise exclusive operator of 5 and 3 is 6
Result of bitwise left shift operator of 5 and 3 is 40
Result of bitwise right shift operator of 5 and 3 is 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;
The pictorial representation of the above syntax is shown below:
Meaning of the above 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.
Let's understand the ternary or conditional operator through an example.
- #include <stdio.h>
- Int main()
- {
- Int age; // variable declaration
- Printf("Enter your age");
- Scanf("%d",&age); // taking user input for age variable
- (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
- Return 0;
- }
In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e., (printf("not eligible for voting")).
Let's observe the output of the above program.
If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:
As we can observe from the above two outputs that if the condition is true, then the statement1 is executed; otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and based on condition, it executes the statements. Now, we will see how a conditional operator is used to assign the value to a variable.
Let's understand this scenario through an example.
- #include <stdio.h>
- Int main()
- {
- Int a=5,b; // variable declaration
- b=((a==5)?(3):(2)); // conditional operator
- Printf("The value of 'b' variable is : %d",b);
- Return 0;
- }
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value otherwise 2.
Output
The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is equal to 5.
As we know that the behavior of conditional operator and 'if-else' is similar but they have some differences. Let's look at their differences.
- A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis.
- A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose.
- It is not useful for executing the statements when the statements are multiple, whereas the 'if-else' statement proves more suitable when executing multiple statements.
- The nested ternary operator is more complex and cannot be easily debugged, while the nested 'if-else' statement is easy to read and maintain.
Special Operators in C:
Below are some of the special operators that the C programming language offers.
Operators | Description |
& | This is used to get the address of the variable. Example : &a will give address of a. |
* | This is used as pointer to a variable. Example : * a where, * is pointer to the variable a. |
Sizeof () | This gives the size of the variable. Example : size of (char) will give us 1. |
Example program for & and * operators in C:
In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to get the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more about pointers.
1 2 3 4 5 6 7 8 9 10 11 | #include <stdio.h> Int main() { Int *ptr, q; q = 50; /* address of q is assigned to ptr */ Ptr = &q; /* display q's value using ptr variable */ Printf("%d", *ptr); Return 0; } |
Output:
50 |
Example program for sizeof() operator in C:
Sizeof() operator is used to find the memory space allocated for each C data types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #include <stdio.h> #include <limits.h>
Int main() { Int a; Char b; Float c; Double d; Printf("Storage size for int data type:%d \n",sizeof(a)); Printf("Storage size for char data type:%d \n",sizeof(b)); Printf("Storage size for float data type:%d \n",sizeof(c)); Printf("Storage size for double data type:%d\n",sizeof(d)); Return 0; } |
Output:
Storage size for int data type:4 Storage size for char data type:1 |
Continue on types of C operators:
Click on each operator name below for detailed description and example programs.
Types of Operators | Description |
Arithmetic operators | These are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus |
Assignment operators | These are used to assign the values for the variables in C programs. |
Relational operators | These operators are used to compare the value of two variables. |
Logical operators | These operators are used to perform logical operations on the given two variables. |
Bit wise operators | These operators are used to perform bit operations on given two variables. |
Conditional (ternary) operators | Conditional operators return one value if condition is true and returns another value is condition is false. |
Increment/decrement operators | These operators are used to either increase or decrease the value of the variable by one. |
Special operators | &, *, sizeof( ) and ternary operators. |
Unary operator
Only one operand is required to perform calculation.
++(increment operator)
-- (decrement operator)
Example
a = 5;
++a;
--a;
Binary Operator
Two operands are required to perform calculation.
+, -, *, % etc.
Example
a = 5;
b = 15;
a + b;
a - b;
Ternary Operator
Three operands are required to perform calculation.
Example
(expression 1)? (expression 2): (expression 3);
a > b?printf("a"):printf("b");
It is also called as a conditional operator in c.
Arithmetic Expressions consist of numeric literals, arithmetic operators, and numeric variables. They simplify to a single value, when evaluated.
Here is an example of an arithmetic expression with no variables:
3.14*10*10
This expression evaluates to 314, the approximate area of a circle with radius 10. Similarly, the expression
3.14*radius*radius
Would also evaluate to 314, if the variable radius stored the value 10.
Note that the parentheses in the last expression helps dictate which order to evaluate the expression.
Multiplication and division have a higher order of precedence than addition and subtraction. In an arithmetic expression, it is evaluated left to right, only performing the multiplications and divisions.
After doing this, process the expression again from left to right, doing all the additions and subtractions.
So,
3+4*5
First evaluates to
3+20 which then evaluates to 23.
Consider this expression:
3 + 4*5 - 6/3*4/8 + 2*6 - 4*3*2
First go through and do all the multiplications and divisions:
3 + 20 - 1 + 12 - 24
Integer Division: In particular, if the division has a leftover remainder or fraction, this is simply discarded.
For example:
13/4 evaluates to 3
19/3 evaluates to 6 but
Similarly, if you have an expression with integer variables part of a division, this evaluates to an integer as well.
For example, in this segment of code, y gets set to 2.
Int x = 8;
Int y = x/3;
However, if we did the following,
Double x = 8;
Double y = x/3;
y would equal 2.66666666 (approximately).
The way C decides whether it will do an integer division (as in the first example), or a real number division (as in the second example), is based on the TYPE of the operands.
If both operands are ints, an integer division is done.
If either operand is a float or a double, then a real division is done. The compiler will treat constants without the decimal point as integers, and constants with the decimal point as a float. Thus, the expressions 13/4 and 13/4.0 will evaluate to 3 and 3.25 respectively.
The mod operator (%)
The one new operator is the mod operator, which is denoted by the percent sign(%). This operator is ONLY defined for integer operands. It is defined as follows:
a%b evaluates to the remainder of a divided by b.
For example,
12%5 = 2
19%6 = 1
14%7 = 0
19%200 = 19
The precedence of the mod operator is the same as the precedence of multiplication and division.
Implicit &Explicit
What is Typecasting in C?
Typecasting is converting one data type into another one. It is also called as data conversion or type conversion. It is one of the important concepts introduced in 'C' programming.
'C' programming provides two types of type casting operations:
Implicit type casting
Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.
Implicit type conversion happens automatically when a value is copied to its compatible data type. During conversion, strict rules for type conversion are applied. If the operands are of two different data types, then an operand having lower data type is automatically converted into a higher data type. This type of type conversion can be seen in the following example.
#include<stdio.h>
Int main(){
Short a=10; //initializing variable of short data type
Int b; //declaring int variable
b=a; //implicit type casting
Printf("%d\n",a);
Printf("%d\n",b);
}
Output
10
10
- In the given example, we have declared a variable of short data type with value initialized as 10.
- On the second line, we have declared a variable of an int data type.
- On the third line, we have assigned the value of variable s to the variable a. On third line implicit type conversion is performed as the value from variable s which is of short data type is copied into the variable a which is of an int data type.
Converting Character to Int
Consider the example of adding a character decoded in ASCII with an integer:
#include <stdio.h>
Main() {
Int number = 1;
Char character = 'k'; /*ASCII value is 107 */
Int sum;
Sum = number + character;
Printf("Value of sum : %d\n", sum );
}
Output:
Value of sum : 108
Here, compiler has done an integer promotion by converting the value of 'k' to ASCII before performing the actual addition operation.
Arithmetic Conversion Hierarchy
The compiler first proceeds with promoting a character to an integer. If the operands still have different data types, then they are converted to the highest data type that appears in the following hierarchy chart:
Consider the following example to understand the concept:
#include <stdio.h>
Main() {
Int num = 13;
Char c = 'k'; /* ASCII value is 107 */
Float sum;
Sum = num + c;
Printf("sum = %f\n", sum );}
Output:
Sum = 120.000000
First of all, the c variable gets converted to integer, but the compiler converts num and c into "float" and adds them to produce a 'float' result.
Important Points about Implicit Conversions
- Implicit type of type conversion is also called as standard type conversion. We do not require any keyword or special statements in implicit type casting.
- Converting from smaller data type into larger data type is also called as type promotion. In the above example, we can also say that the value of s is promoted to type integer.
- The implicit type conversion always happens with the compatible data types.
We cannot perform implicit type casting on the data types which are not compatible with each other such as:
- Converting float to an int will truncate the fraction part hence losing the meaning of the value.
- Converting double to float will round up the digits.
- Converting long int to int will cause dropping of excess high order bits.
In all the above cases, when we convert the data types, the value will lose its meaning. Generally, the loss of meaning of the value is warned by the compiler.
'C' programming provides another way of typecasting which is explicit type casting.
Explicit type casting
In implicit type conversion, the data type is converted automatically. There are some scenarios in which we may have to force type conversion. Suppose we have a variable div that stores the division of two operands which are declared as an int data type.
Int result, var1=10, var2=3;
Result=var1/var2;
In this case, after the division performed on variables var1 and var2 the result stored in the variable "result" will be in an integer format. Whenever this happens, the value stored in the variable "result" loses its meaning because it does not consider the fraction part which is normally obtained in the division of two numbers.
To force the type conversion in such situations, we use explicit type casting.
It requires a type casting operator. The general syntax for type casting operations is as follows:
(type-name) expression
Here,
- The type name is the standard 'C' language data type.
- An expression can be a constant, a variable or an actual expression.
Let us write a program to demonstrate implementation of explicit type-casting in 'C'.
#include<stdio.h>
Int main()
{
Float a = 1.2;
//int b = a; //Compiler will throw an error for this
Int b = (int)a + 1;
Printf("Value of a is %f\n", a);
Printf("Value of b is %d\n",b);
Return 0;
}
Output:
Value of a is 1.200000
Value of b is 2
- We have initialized a variable 'a' of type float.
- Next, we have another variable 'b' of integer data type. Since the variable 'a' and 'b' are of different data types, 'C' won't allow the use of such expression and it will raise an error. In some versions of 'C,' the expression will be evaluated but the result will not be desired.
- To avoid such situations, we have typecast the variable 'a' of type float. By using explicit type casting methods, we have successfully converted float into data type integer.
- We have printed value of 'a' which is still a float
- After typecasting, the result will always be an integer 'b.'
In this way, we can implement explicit type casting in 'C' programming.
Summary
- Typecasting is also called as type conversion
- It means converting one data type into another.
- Converting smaller data type into a larger one is also called as type promotion.
- 'C' provides an implicit and explicit way of type conversion.
- Implicit type conversion operates automatically when the compatible data type is found.
- Explicit type conversion requires a type casting operator.
Keep in mind the following rules for programming practice when dealing with different data type to prevent from data loss :
- Integers types should be converted to float.
- Float types should be converted to double.
- Character types should be converted to integer.
Precedence and Associativity
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Example Code
#include <stdio.h>
Main() {
Int a = 20;
Int b = 10;
Int c = 15;
Int d = 5;
Int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
Printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
Printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
Printf("Value of a + (b * c) / d is : %d\n" , e );
Return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
Implicit type conversion:
Also known as ‘automatic type conversion’.
- Done by the compiler on its own, without any external trigger from the user.
- Generally, takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid to loose data.
- All the data types of the variables are upgraded to the data type of the variable with largest data type.
Bool -> char -> short int -> int ->
Unsigned int -> long -> unsigned ->
Long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted to unsigned), and overflow can occur (when long is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion #include<stdio.h> Int main() { Int x = 10; // integer x Char y = 'a'; // character c
// y implicitly converted to int. ASCII // value of 'a' is 97 x = x + y;
// x is implicitly converted to float Float z = x + 1.0;
Printf("x = %d, z = %f", x, z); Return 0; } |
|
Output:
x=107, z = 108.000000
Explicit Type Conversion–
This process is also called type casting and it is user defined. Here the user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the result is converted.
// C program to demonstrate explicit type casting #include<stdio.h>
Int main() { Double x = 1.2;
// Explicit conversion from double to int Int sum = (int)x + 1;
Printf("sum = %d", sum);
Return 0; }
Output:
Sum =2
Advantages of type conversion:
This is done to take advantage of certain features of type hierarchies or type representations.
It helps us to compute the expression containing variables of different data types. |