You are on page 1of 16

Operators in C

=
In this tutorial, you will learn about different operators in C programming.
An operator is a symbol that instructs a computer to perform certain operations.
Operators are typically used as part of mathematical or logical expressions. C supports a
rich set of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operators such as addition, subtraction
etc. C supports all basic arithmetic operators. The list of all arithmetic operators in C is
listed in the following table.
OPERATOR MEANING EXAMPLE
+ Addition or Unary plus 8 + 2 = 10
– Subtraction or Unary minus 8–2 6
* Multiplication 8 * 2 = 16
/ Division 8/2=4
% Modulo division 13 % 2 = 1
The unary plus and unary minus operators are used to specify the sign of a number. The
modulo division (%) operator produces the remainder of an integer division. For example
10 % 3 = 1.

The variables in which the operation is performed is called operand. That is, in a + b, a
and b are operands and + is the operator.
When the operands in a single arithmetic expression are both integers, then the operation
is known as integer arithmetic. Integer arithmetic always produces an integer value as
output. All the examples in the above table are integer arithmetic. For example: 12 / 10 =
1

Real arithmetic refers to arithmetic operations that will use only real operands. The
operator % cannot be used with real operands. For example: 3.0 / 2.0 = 1.5
Mixed-mode arithmetic expressions are those in which one of the operands is real and
the other is an integer. Since one of the operands is of real type, then the result is always
a real number. For example: 12 / 10.0 = 1.2
Example: Arithmetic operators
#include <stdio.h>
int main()
{
int a = 8,b = 2, c;

c = a+b;
printf("Sum = %d \n",c);
c = a-b;
printf("Difference = %d \n",c);
c = a*b;
printf("Product = %d \n",c);
c = a/b;
printf("Quotient = %d \n",c);
c = a%b;
printf("Remainder after division = %d \n",c);

return 0;
}

Output
Sum = 10
Difference = 6
Product = 16
Quotient = 4
Remainder after division = 0

C Relational Operators
The relationship operators are used to check the relationship between two operands. The
value of a relational operator is either 1 (true) or 0 (false). The list of relational operators
supported in C is given in the table. Suppose a = 6 and b = 2.
OPERATOR MEANING EXAMPLE
< is less than a < b is true.
<= is less than or equal to a <= b is true
> is greater a > b is false
-
=
>= is grater than an equal to a >= b is false
== is equal to a == b is false
! is not equal to a ! b is true
Note that the arithmetic operators have a higher priority over relational operators. For
example, in the expression 10 < 7 + 5 , 7 + 5 is evaluated first and the result 12 is
compared with 10.
Relational statements are generally used in decision-making statements and loops.
Example: Relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 4;

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


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

return 0;
}

Output
5 == 4 is 0
5 > 4 is 1
5 < 4 is 0
5 != 4 is 1
5 >= 4 is 1
5 <= 4 is 0

C Logical Operators
The logical operators are used to make a decision by testing one or more conditions. The
three logical operators supported in C are:
&& – logical AND – True only if all operands are true.

|| – logical OR – True only if either one operand is true.

! – logical NOT – True only if the operand is 0

The value of a logical operator is also one or zero according to the truth table given
below:
A B A && B A || B !A
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0

C Assignment Operator
Assignment operators are used to assigning values to a variable. The assignment
operator in c is =. C also has a set of shorthand assignment operators as shown in the
table:
OPERATOR EXAMPLE SAME AS
+= a += b a=a+b
-= a -= b a=a–b
*= a *= b a=a*b
OPERATOR EXAMPLE SAME AS
/= a /= b a=a/b
% a% b a=a%b

C Increment and Decrement Operator


=
=
In C, the operators ++ and -- are called the increment and decrement operators and are
used to change the value of an operand by 1.
The increment operator ++ increases the value of an operand by 1 and the decrement
operator -- decreases the value of an operand by 1. They both are unary operators.
These operators can be used as prefixes like ++a and can be used as postfixes like a++.
You can learn the difference in increment and decrement operators when used as prefix
and postfix here.
C Bitwise Operator
For manipulation of data at bit level, C supports special operators known as bitwise
operators. Bit wise operators and their meaning is given in the following table:
OPERATOR MEANING
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
` Bitwise complement
<< Shift left
>> Shift right

C Conditional Operator
C has a special ternary operator ?: called conditional operator. The conditional operator
behaves similarly to the ‘if-else’ statement. The syntax of a conditional operator is as
follows:
condition ? true-statement : false-statement;

Here expression1 is a boolean condition that can be either true or false. The conditional
operator will return expression2, if the value of expression1 is true. Similarly, if the value of
expression1 is false, then the operator will return expression3. For example, consider the

following example:
max = (a > b) ? a : b ;

First, the expression a > b is evaluated. If it is true, the statement will be equivalent to max
= a;. If a > b is false, then the statement will be equivalent to max = b.

Special Operators
C also support some special operators such as comma operator, sizeof operator, pointer
operators, etc.
The Comma Operator
The comma operator is used to link the related expression together. For example:
float a, b, c;

The sizeof Operator


The sizeof operator return the number of bytes a operand occupies. It can be used to
know the size of variables, constants, arrays, structures etc. For example:
x = sizeof(mark);

Other operators
The reference operator & and deference operator * is used in pointer operations. The
member selection operator . and -> are used to select members of a structure. These
operators will be discussed in later tutorials.
Arithmetic Expressions and Operator
Precedence in C
An arithmetic expression is a combination of variables, constants, and arithmetic
operators. Arithmetic operators supported in C are +, -, *, / and %. The operands include
integer and floating-type numbers. Some algebraic expressions and their corresponding
C expressions are given in the following table.
ALGEBRAIC EXPRESSION C EXPRESSION
(a + b) * (a-b)

(a * b) / c

2*x*x+3*x

Arithmetic expressions are evaluated using an assignment statement of the form variable
= expression. The expression is evaluated first and the value is assigned to the variable.

An example of an evaluation statement is, c = a - b / d + e


Precedence of Arithmetic Operators in C
To determine the meaning and value of an expression in an unambiguous manner, we
apply the operator precedence and associativity rules. Arithmetic expressions without
parentheses are evaluated from left to right using the rules of operator precedence. In C,
arithmetic operators have two different priority levels.
Hight priority * / %
Low priority + -
The basic procedure for evaluating an expression includes two passes from left to right.
The high priority operators are applied during the first pass and the low priority operators
are applied in the second pass.
For example, the statement x = 8 – 15 / 5 + 2 * 5 – 7 is evaluated as follows,
First pass
x = 8 - 5 + 2 * 5 -7

x = 8 - 5 + 10 - 7

Second pass
x = 3 + 10 - 7

x = 13 - 7

x = 6

These steps are illustrated in the following figure.

However, parentheses can be used to change the order in which an expression is


evaluated. The expression within parentheses assumes the highest priority. The following
rules are used for evaluating expressions containing parentheses.
Parenthesized subexpressions are evaluated from left to right.
When there are nested parentheses, the evaluation starts with the innermost sub-
expression.
The order of application of operators in evaluating sub-expressions is determined using
the precedence rule.
When two or more operators with the same precedence level exist in a sub-expression,
the associativity rule is applied.
Arithmetic expressions are evaluated from left to right using the rules of precedence.
The expressions within parentheses assume the highest priority.
For example, the statement x = 8 – 14 / (5 + 2) * (8 – 7) is evaluated as follows,
First pass
x = 8 - 14 / 7 * (8 -7)
x = 8 - 14 / 7 * 1

Second pass
x = 8 - 2 * 1

x = 8 - 2

Third pass
x = 6

Operator Precedence and Associativity in C


The following table shows the complete list of C operators, their precedence levels, and
their rules of association.
OPERATOR DESCRIPTION ASSOCIATIVITY RANK
() Function call
Left to right 1
[] Array element reference
+ Unary plus
– Unary minus
++ Increment
— Decrement
! Logical negation
Right to left 2
~ Ones complement
* Pointer reference
& Address
sizeof Size of an object
(type) Type cast (conversion)
* Multiplication
/ Division Left to right 3
% Modulus
+ Addition
Left to right 4
– Subtraction
OPERATOR DESCRIPTION ASSOCIATIVITY RANK
<< Left shift
Left to right 5
:
>> Right shift
=
< Less than
<= Less than or equal to
Left to right 6
> Greater than
>= Greater than or equal to
== Equality
Left to right 7
! Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
? Conditional operator Right to left 13
= Assignment operator Right to left 14
, Comma operator Left to right 15
TYPE CONVERSION IN EXPRESSIONS
It 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. There are two types of type conversion:
1. Implicit Type Conversion. 2. Explicit Type Conversion.

1. Implicit Type Conversion: The type conversion is the process of converting a data value from one data type to another
data type automatically by the compiler. Sometimes type conversion is also called implicit type conversion. The implicit
type conversion is automatically performed by the compiler. Also known as ‘automatic type conversion’.
For example, in c programming language, when we assign an integer value to a float variable the integer value automatically
gets converted to float value by adding decimal value 0. And when a float value is assigned to an integer variable the float
value automatically gets converted to an integer value by removing the decimal value.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i=x;
printf("i value is %d\n",i);
x=i;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}

All the data types of the variables are upgraded to the data type of the variable with largest data type.
#include<stdio.h>
main()
{
int x = 10; // integer x
char y = 'a'; // character c

x = x + y; // y implicitly converted to int. ASCII value of 'a' is 97


float z = x + 1.0; // x is implicitly converted to float
printf("x = %d, z = %f", x, z);
}
Output: x = 107, z = 108.000000
2. 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. To perform this we use the unary cast operator. To convert data from one type to
another type we specify the target data type in parenthesis as a prefix to the data value that has to be converted.
The general syntax of typecasting is: (TargetDatatype) DataValue;
#include<stdio.h>
main ()
{
double x = 1.2;
int sum = (int)x + 1; // Explicit conversion from double to int
printf("sum = %d", sum);
}
Output: sum = 2
#include<stdio.h>
void main()
{
int a, b, c ;
float avg ;
printf( "Enter any three integer values : ");
scanf(“%d %d %d”,&a,&b,&c);
avg = (float)(a + b + c) / 3 ;
printf( "Average after casting = %d",avg);
}
Output: Enter any three integer values: 10 20 30
Average after casting = 20.000000

Mathematical Functions
The different mathematical functions used in C programming languages with working code. The C languages use
header/library called Math.h for various mathematical functions. This helps in calculating trigonometric operations,
logarithms, absolute values, square roots. So, let us explore the different types of functions used in this library. All these
functions take double as a data type and return the same. To implement the below functions, it is mandatory to
include<cmath.h> or <math.h> in the code.
1. floor () 6. trun() 11. cosh()
2. ceil () 7. fmod() 12. tan()
3. Sqrt () 8. sin() 13. tanh()
4. round () 9. sinh() 14. Exp()
5. pow () 10. cos() 15. log()
Examples:
1. floor (7.2) is 7.0 6. trun(56.16) is 56.000000 12. tan(30) is 0.58
floor (-7.2) is -8.0 trun(85.74) is 85.000000 13. tanh(1.20) is 0.83

2. ceil(12.60) is 13.0000 7. fmod(10,3) is 1.000000 14. Exp(6) is 403.428793


3. Sqrt(4.00) is 2.000000 8. sin(45.00) is 85.00 15. log(1) is 0
4. round (23.2) is 23.0 9. sinh(3.60) is 18.29
round (23.7) is 24.0
round (23.0) is 23.0 10. cos(45.000000) is 0.707388

5. pow (5,3) is 125 11. cosh(0.600000) is 1.185465

1. floor (double a) :This function returns rounded down to the nearest integer.
2. ceil() : This function returns rounded up to the nearest integer.
3. Sqrt () :This function returns the square root of a specified number.
4. round () :This function rounds the nearest value of a given input.
5. pow () :This function returns to power for the given number (ab). It returns a raised to the power of b.
6. trun() :This function helps in truncating the given value. It returns integer values.
7. fmod() :This function returns the remainder for the given two input values when m divided by n.
8. sin() :This built-in function gives sine value of the given number.
9. sinh ():It returns hyperbolic sine for a given value.
10. cos() :This math function determines the trigonometric cosine value for the given element.
11. cosh() :It returns hyperbolic cosine for a given value.
12. tan() :This math library function calculates tangent values of the angle for the mathematical expression.
13. tanh() :tanh() function returns hyperbolic tangent of the given value.
14. exp() :This function does computation on exponential for a given value(ex).
15. log() :This function returns the logarithm value of a given number. (to the base e. loge)
I/O Operations -Library Functions
Input means to provide the program with some data to be used in the program and Output means to display data on screen
or write the data to a file.C programming language provides many built-in functions to read any given input and to display
data on screen when there is a need to output the result.
 The basic input/output functions are getchar, putchar, gets, puts, scanf and printf.
 The first two functions, getchar and putchar, are used to transfer single character like input and output Character .
 The next two functions function gets and puts is used to input strings and output strings.
 The scanf and printf, permit the transfer of single characters, numerical values and strings.
 isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero
value if it’s a digit else it returns 0. For example, it returns a non-zero value for ‘0’ to ‘9’ and zero for others.
 isalpha(c) is a function in C which can be used to check if the passed character is an alphabet or not. It returns a non-
zero value if it’s an alphabet else it returns 0. For example, it returns non-zero values for ‘a’ to ‘z’ and ‘A’ to ‘Z’ and
zeroes for other characters.
 fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered
data to console (in case of stdout) or disk (in case of file output stream).
High level I/O Functions : Format Specifiers for I/O: Examples :
 %d for int scanf("%d", &i);
Function Description
 %f for float printf( "%d", i);
fprintf ( ) write data into a file
 %lf for double c = getchar();
fscanf ( ) read data from a file
putc ( )/ fputc() write a character into a file  %c for char putchar(c);
 %Lf for long double char str[100];
getc ( ) /fgetc() read a character from a file
 %li for long int gets( str );
putw ( ) write a number into a file
 %lli for long long int puts( str );
getw ( ) read number from a file
getch();
fputs ( ) write a string into a file
fflush(stdin);
fgets ( ) read a string from a file
fread() read an entire record from a file
fwrite() write an entire record into a file

Case Study (Expression Evaluation)

Expssn : a + b && b / c % d * e || 5 <= 0 != a + b – d Assume that the value of a = 5, b = 6, c = 8, d = 2, and e = 1.

Solution: 5 + 6 && 6 / 8 % 2 * 1 || 5 <= 0 != 5 + 6 – 2 (substitute values)

5 + 6 && 0 % 2 * 1 || 5 <=0 != 5 + 6 – 2 (6 / 8 evaluated)

5 + 6 && 0 * 1 || 5 <= 0 != 5 + 6 – 2 (0 % 2 evaluated)

5 + 6 && 0 || 5 <= 0 != 5 + 6 – 2 (0 * 1 evaluated)

11 && 0 || 5 <= 0 != 5 + 6 – 2 (5 + 6 evaluated)

11 && 0 || 5 <= 0 != 11 – 2 (5 + 6 evaluated)

11 && 0 || 5 <= 0 != 9 (11 – 2 evaluated)

11 && 0 || 0 != 9 (5 <= 0 evaluated)

11 && 0 || 1 (0 != 9 evaluated)

0 || 1 (11 && 0 evaluated)

1 (0 || 1 evaluated)

**********************************
HAPPY
LEARNING

Visit www.teachics.org for Computer Science Tutorials, Programming


Examples, Interview Questions and much more.

You might also like