0% found this document useful (0 votes)
20 views15 pages

COSC 206 Lecture 3

The document provides an overview of operators and expressions in C programming, detailing various types of operators including arithmetic, assignment, relational, logical, increment/decrement, conditional, bitwise, and special operators. Each operator type is explained with examples and sample code demonstrating their usage. Additionally, the document covers operator precedence and includes exercises for practice.

Uploaded by

dlovefky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views15 pages

COSC 206 Lecture 3

The document provides an overview of operators and expressions in C programming, detailing various types of operators including arithmetic, assignment, relational, logical, increment/decrement, conditional, bitwise, and special operators. Each operator type is explained with examples and sample code demonstrating their usage. Additionally, the document covers operator precedence and includes exercises for practice.

Uploaded by

dlovefky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

COSC 206

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.

Increment/decrement These operators are used to either increase or


5 decrease the value of the variable by one.
operators
These operators are used to perform bit operations on
6 Bitwise opertors given two variables.

Conditional operators return one value if condition is


Conditional (Tenary)
7 true and returns another value is condition is false.
Operator
&, *, sizeof( ) and ternary operators
8 Special Operators

C ARITHMETIC OPERATORS
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.

S/N Arithmetic Operator Operation Example


1 + Addition X+Y
2 - Subtraction X -Y
3 * Multiplication X*Y
4 / Division X/Y
5 % Modulus X %Y

Example program demonstrating the use of C arithmetic operators


// Working of arithmetic operators
#include <stdio.h>
1
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;
}

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

m and n are not equal

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

Example program demonstrating the use of C Logical operators


// Working of logical operators

#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

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is
inverted as false

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;
}

(b) #include <stdio.h>


int main()
{
int i=10;
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.

Syntax : (Condition? true_value:false_value);

Example : (A > 100 ? 0 :1);

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

BIT WISE OPERATORS


Mathematical operations like: addition, subtraction, multiplication and division are done in bit-
level, in the arithmetic-logic unit (which is within the CPU). To perform bit-level operations in C
programming, bitwise operators are used.
Decimal values are converted into binary values which are the sequence of bits and bit wise
operators work on these bits. C language has the following bitwise operators:
Bitwise Operators
Operator_symbol Operator_name
& Bitwise_AND
| Bitwise OR
~ Bitwise_NOT
8
^ XOR
<< Left Shift
>> Right Shift

Bitwise operators’ truth table


x y x|y x&y x^y
0 0 0 0 0
0 1 1 0 1
1 0 1 0 1
1 1 1 1 0

Consider x=40 and y=80. Binary form of these values are given below.

x =00101000
y= 01010000

All bit wise operations for x and y are given below.

x&y = 00000000 (binary) = 0 (decimal)


x|y = 01111000 (binary) = 120 (decimal)
~x = 11111111111111111111111111 11111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80(decimal)
x >> 1 = 00010100 (binary) = 20(decimal)
Note:
Bit wise NOT: Value of 40 in binary is:
0000000000000000000000000000000000000000000000000010100000000000. So, all 0‘s are
converted into 1‘s in bit wise NOT operation.
Bit wise left shift and right shift:
In left shift operation -x << 1 -, 1 means that the bitswill be left shifted by one place. If we use it
as -x << 2 -, then, it means that the bitswill be left shifted by 2 places.
Example Program Demonstrating the Use of Bit Wise Operators in C
//working of bitwise operators
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
9
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Sample output

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.

Example program demonstrating the use of & and * operators in C


//working address and pointer operators
#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;
}

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

Storage size for int data type: 4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

OPERATOR PRECEDENCE AND ASSOCIATIVITY IN C


Operator precedence in c determines the order in which the operators will be evaluated in an
expression. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator.
In the following expression
x = 7 + 3 * 2;
x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied
with 3*2 and then adds into 7.

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

Value of sum : 116.000000

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() {

// create an integer variable


int number = 97;
printf("Integer Value: %d\n", number);

// (char) converts number to character


char alphabet = (char) number;
printf("Character Value: %c", alphabet);

return 0;
}

Sample output

Integer value: 97
Character
Input value: a
and output

15

You might also like