COSC 206 Lecture 3
COSC 206 Lecture 3
Introduction to C programming
Lecture 3: Operators and Expressions in C
Operators are symbols used to perform operations on values or variables. For example, + is used
for performing mathematical addition in C. C language supports a wide range of operators for
performing various operations.
C OPERATORS AND THEIR DESCRIPTION
S/N Types of Operators Description
These are used to perform mathematical calculations
1 Arithmetic_operators like addition, subtraction, multiplication, division
and modulus
These are used to assign the values for the variables
2 Assignment_operators
in C programs.
These operators are used to compare the value of two
3 Relational operators
variables.
These operators are used to perform logical operations on
4 Logical operators the given two variables.
C ARITHMETIC OPERATORS
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
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;
}
Sample Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
ASSIGNMENT OPERATORS
In C programs, values for variables are assigned using assignment operators. For example, if the
value 10 is to be assigned to the variable sum, it can be assigned as follows
sum = 10;
Other assignment operators in C language are given below.
S/N Operator Example Same as
1 = a=b a=b
2 += a += b a = a+b
3 -= a -= b a = a-b
4 *= a *= b a = a*b
5 /= a /= b a = a/b
6 %= a %= b a = a%b
2
Example program demonstrating the use of C assignment operators
// Working of assignment operators
#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;
}
Sample output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
RELATIONAL OPERATORS
Relational operators are used to find/check the relation/relationship between two variables. i.e. to
compare the values of two variables in a C program. If the relation is true, it returns 1; if the relation
is false, it returns value 0. Relational operators are mostly used in decision making and loops.
C has the following relational operators:
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
3
Example program demonstrating the use of C relational operators
// Working of relational operators
#include<stdio.h>
int main()
{
int m=40, n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
return 0;
}
Sample output
LOGICAL OPERATORS
Logical operators are used to perform logical operations on the given expressions. C supports
3 logical operators. They are, logical AND (&&), logical OR (||) and logical NOT (!). 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.
Operator Meaning Example
&& Logical AND. True only if all If c = 5 and d = 2 then, expression ((c==5) &&
operands are true (d>5)) equals to 0.
|| Logical OR. True only if either If c = 5 and d = 2 then, expression ((c==5) ||
one operand is true (d>5)) equals to 1.
! Logical NOT. True only if the If c = 5 then, expression!(c==5) equals to 0.
operand is 0
#include <stdio.h>
4
int main()
{
int x=40,y=20;
int a=20,b=30;
if (x>y && x !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (a>b || b!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(x>y && x !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " "But, status is inverted as false\n");
}
}
Sample Output
INCREMENT/DECREMENT OPERATORS
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs. These two operators
are unary operators, meaning they only operate on a single operand (variable).
Syntax:
Increment operator: ++var_name ;( or) var_name++;
Decrement operator: - -var_name; (or) var_name --;
Example:
Increment operator : ++i; i ++ ;
Decrement operator : – – i ; i – – ;
Example program demonstrating the use of C increment operator
// Working of increment operator in C
5
#include <stdio.h>
int main()
{
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Sample Output
123456789
In the above program, value of i is incremented one by one from 1 up to 9 using i++ operator
and output is displayed as :1 2 3 4 5 6 7 8 9.
Example program demonstrating the use of C decrement Operator
//Working of decrement operators
#include <stdio.h>
int main()
{
int i= 20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
Sample output
20 19 18 17 16 15 14 13 12 11
In the above program, value of i is decremented one by one from 20 up to 11 using i--
operator and the output is displayed as : 20 19 18 17 16 15 14 13 12 11.
Difference between pre/post increment and decrement
S/N Operator Example Description
Value of i is incremented by 1, then it returns the value
1 Pre –increment ++i
2 Post–increment i++ Value of i is returned first, then it is incremented by 1
Value of i is decremented by 1, then it returns the value
3 Pre decrement - -i
4 Post_decrement i- - Value of i is returned first, then it is decremented by 1
6
Example program to demonstrate pre and post increment operators
//Working of pre and post increment operators
#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; }
Exercise
Write the output of the following programs
(a) #include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
7
CONDITIONAL OR TERNARY OPERATORS IN C
Conditional operators (? :) return one value if condition is true and returns another value is
condition is false. This operator is also called as ternary operator.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
Example program to demonstrate the use of conditional operator in C
//working of conditional operator
#include
<stdio.h>
int main()
{
int x=1, y;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Sample Output
x value is 1
y value is 2
Consider x=40 and y=80. Binary form of these values are given below.
x =00101000
y= 01010000
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
In the above example program, bit wise operations are performed as shown above and output is
displayed in decimal format.
SPECIAL OPERATORS
C supports a number of special operators which include:
S/N Operators Description
This is used to get the address of a variable.
1 &
Example : &a will give address of a.
This is used as pointer to a variable.
2 *
Example: *a where, * is pointer to the variable a.
This gives the size of the variable.
3 Sizeof ()
Example: size of (char) will give us 1.
10
Sample output
50
In the above 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.
Example program demonstrating the use of sizeof() operator in C
sizeof() operator is used to find the memory space allocated for each C data types.
//Working of sizeof() operator
#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 datatype:%d\n",sizeof(d));
return 0;
}
Sample Output
11
The following table show the order of operators in C. the operators are arranged in decreasing
order of precedence with the operator at the top of the table having the highest precedence while
the ones at the bottom has the lowest.
Category Operator Associativity
Bracket/parenthesis () [] 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
Associativity on the other hand defines the order in which the operators of the same precedence
will be evaluated in an expression. Associativity can occur from either right to left or vice versa.
For example,
1 == 2 != 3
Here operators == and != have the same precedence and their associativity is from left to right.
Hence, 1 == 2 is evaluated first.
The above expression is equivalent to:
(1 == 2) != 3
Note:
Parentheses are also used to group sub-expressions to force a different precedence; such
parenthetical expressions can be nested and are evaluated from inner to outer.
12
TYPE CONVERSION
When variables and constants of different types are combined in an expression then they are
converted to same data type. The process of converting one predefined type into another is called
type conversion. Type conversion in C can be classified into the following two types:
Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmer‘s
intervention, such type of conversion is known as implicit type conversion or type promotion.
The compiler converts all operands into the data type of the largest operand. The sequence of rules
that are applied while evaluating expressions are given below:
All short and char are automatically converted to int, then,
If either of the operand is of type long double, then others will be converted to long double and
result will be long double.
Else, if either of the operand is double, then others are converted to double.
Else, if either of the operand is float, then others are converted to float.
Else, if either of the operand is unsigned long int, then others will be converted to unsigned long
int.
etc.
Example program to demonstrate the use of type conversion
//working of implicit type conversion
#include<stdio.h>
int main() {
// character variable
char alphabet = 'a';
printf("Character Value: %c\n", alphabet);
// assign character value to integer variable
int number = alphabet;
printf("Integer Value: %d", number);
return 0;
}
Sample output
Character value: a 13
Integer value: 97
Here, the variable alphabet which is of char type is implicitly converted (promoted) to an integer,
when it was assigned to the integer variable number.
Example program showing the use of type conversion
//working of implicit type conversion
#include <stdio.h>
main() {
int i = 17;
char c = 'c'; /* ascii value is 99 */
float sum;
sum = i + c;
printf("Value of sum : %f\n", sum );
}
Sample output
Here, it is simple to understand that first c gets converted to integer, but as the final value is double,
usual arithmetic conversion applies and the compiler converts i and c into 'float' and adds them
yielding a 'float' result.
Explicit Type Conversion
The type conversion performed by the programmer by manually converting the data type of the
expression of specific type is known as explicit type conversion. The explicit type conversion is
also known as type casting. Type casting in c is done using the following syntax:
(data_type)expression;
where, data_type is any valid data type in C, and expression may be constant, variable or
expression. For example,
x=(int)a+b*d;
Here, the variable a is casted (converted) to integer.
The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
All integer types to be converted to float.
All float types to be converted to double.
All character types to be converted to integer.
Example program to demonstrate the use of explicit type conversion
14
#include<stdio.h>
int main() {
return 0;
}
Sample output
Integer value: 97
Character
Input value: a
and output
15