0% found this document useful (0 votes)
16 views

Script 3 1

This document discusses different types of operators in the C programming language that are used to manipulate data and evaluate expressions. It covers assignment, arithmetic, relational, logical and unary operators as well as the sizeof operator.

Uploaded by

san
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Script 3 1

This document discusses different types of operators in the C programming language that are used to manipulate data and evaluate expressions. It covers assignment, arithmetic, relational, logical and unary operators as well as the sizeof operator.

Uploaded by

san
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

MANIPULATING DATA : OPERATORS AND EXPRESSIONS

1. Introduction

In the previous module we saw that every C programme had void main() or simply
main() as an integral part. The word main must appear one, and only once in every
C program. This is the point where execution begins when the program is run. It
does not have to be the first statement in the programme but it serves as an entry
point.

The term 'main' here is actually a function definition. Functions usually return a
value, and the term ‘void’ is used to denote that the main program does not return a
value. Following the “main” program name is a pair of parentheses, which are an
indication to the compiler that this is a function. We will learn more about functions
later, and we will see that C programs consist essentially of a collection of functions.
The two braces below 'main' are used to define the limits of the programme. We
saw that the actual program statements go between the two braces. We also saw
variables of different types, and how we declare and assign values to a variable.

In this module we will learn more about manipulating data using a C programme.

The basic data structure used in C programs is a number. C provides for two types
of numbers - integers and floating point numbers. Computer operations that involve
text, or character strings, also work essentially on numbers. The possible values of
an 'int' variable in C ranges from -32,768 to 32,767. Whereas character variables,
denoted by the data type 'char', use numbers from 0 to 255 to represent characters.
This number is called the ASCII equivalent of the character. The limit of 256 comes
from the fact that only one byte, or 8 bits, of memory is used to store one character.
All the operations possible on integers are possible on character data also.

Note that the data definitions are always given before any executable statements in
any program block in C. This is why the variables are defined first in any C
programme.

2. Expressions and Operators

In C, a variable or a number or a character is the basic form of an 'expression'.


The value of such an expression is the value of the number, or variable, or the
character. Compound expressions are formed using operators that connect smaller

1
expressions. For example, 5 is an expression that has value 5, a is an expression
and the value is the same as the value of the variable a. 5 + 3 is an expression that
has value 8. a / b is another expression and the value depends on the values of a
and b.

Assignment operators

There are many assignment operators in C. They assign the value of an expression
to an identifier.

The most commonly used assignment operator is = . Usual Syntax of assignment


expression is

identifier = expression;

Example a = 5; b = c / a; here a, b, c are variables

An assignment operation assigns the value of what the right hand side of the
operator '=' evaluates to, to the variable on the left hand side. The left-hand
operand of an assignment operation must be a variable identifier, and on the right
hand side we have the 'assignment expression'. Note that we cannot write
5 = a + b;
a + c = 5;

We can use many assignment operators in a single line, and the operator has right-
to-left associativity. It means that the operations on the right side are carried out
first.

For example,
a = b = c = 25;
The compiler finds the value 25, assigns it to c, then continues to the left. It assigns
the value of c to b, and then that value gets assigned to a.

It is equivalent to having three statements in a sequence: c = 25; b = c; a = b;

This is a very useful construct when we are initializing a group of variables.

a = b = c = 12*3; can also be understood in a similar fashion.

But we cannot have something like a = b * c = 15;


because b * c = 15; is not a valid assignment operation.

There are also other assignment operators like multiplication assignment (*=),

2
addition assignment (+=), Division assignment (/=), Subtraction assignment (-=) etc.

a += 5; is equivalent to writing a = a + 5;
and b /= 2.5; means b = b / 2.5;

A full list of assignment operators can be seen on the screen.


Operator Operation Performed
= Simple assignment
*= Multiplication assignment
/= Division assignment
%= Remainder assignment
+= Addition assignment
–= Subtraction assignment
<<= Left-shift assignment
>>= Right-shift assignment
&= Bitwise-AND assignment
^= Bitwise-exclusive-OR assignment
|= Bitwise-inclusive-OR assignment

Binary arithmetic operators

The most commonly used arithmetic operations are of the form a + 5 or 3 / 4 or c *


2. The basic arithmetic operators, addition (+), subtraction (-), multiplication (*) and
division (/) behave as we expect them to. Ambiguities arise only when there is a
combination of such operations. To resolve such situations, there are rules as to
which operations get the precedence, and when it is between two operations of
same precedence, whether to go from left to right or from right to left.

* and / have higher precedence compared to + and -. All these four operations are
left-to-right associative. It means that 2 + 3 * 5 refers to 2 + (3 * 5), and 2 - 3 - 4
refers to (2-3) - 4.

As you see, these operators work on two operands, or two numbers, at a time. That
is why they are called binary operators.

Apart from these four basic operators, there is modular division, using the %, or the
modulo operator. It gives the remainder when the first variable is divided by the
second. It can only be applied to int or char type variables, and to extended integer
variables such as long, short, etc.

For example, x modulo 4 (written as x % 4) stands for the remainder when an


integer x is divided by 4, and 5 modulo 2 evaluates to 1.

3
The result of an arithmetic operation is determined by the data types of the
operands. For example, in the following expression 2.5 * 3 evaluates to 7.5, a
floating point number.

But if we assign this value to another variable using an assignment operator, the
value that gets assigned will depend on the type of the destination variable.

For instance, x = 2. 5 * 3; will assign the value 7 to x if x is an integer variable, and


7.5 if x is a 'floating point' variable. Note that the type casting occurs after the
calculation has been performed. Otherwise this would have assigned value 6 to x if
x was an integer.

Unary arithmetic operators

Other than the binary operators, C supports relatively less intuitive 'unary'
operations like ++ and - -. They work on a single operand, or on a single variable.

It can appear as a prefix or a suffix operator, i.e, ++a; or a++. Same is the case with
--. ++a; (or a++;), as stand-alone statements, are both equivalent to the statement
a = a + 1;

Similarly, --a; and a--; are equivalent to a = a - 1;

But they become slightly more complicated when used in assignments. ++ as a


prefix assigns the value of the variable before incrementing it, whereas ++ as a
suffix assigns the value after the unary increment operation.

Similar the case of -- operator.

We will see this difference using an example. See the following sequence of
statements.

x = 5; // assigns value 5 to x
x++; // increments x, x becomes 6
++x; // increments x, x becomes 7
c = x++; // c gets assigned the old value of x (7), increments x (to 8)
b = ++x; // increments x again (to 9), and b gets assigned the new value (9)

Similarly for the unary decrement also.

4
b = --x; // first decrements x (to 8), and b gets value 8
c = x--; // c gets value 8, x becomes 7

sizeof operator

This operator returns the size of the operand in bytes. The syntax is
sizeof(<variable name>). For example, sizeof(x). The ‘sizeof’ operator always
precedes its operand. If the operand is an integer, ‘sizeof’ will return the value 2 and
it means that an integer is represented using two bytes. If it is float, the value
returned will be 4 and if it is double it will be 8 , if operand is a char, it will be 1 only.

Relational and Logical operators

Condition expressions are usually represented in C through the use of ‘relational’


operators.

There are four relational operators in C. They are < ( less than ), <= ( less than or
equal to ), > ( greater than) and >= ( grater than or equal to )

In addition to these operators there are two equality operators also in C . They are
== ( equal to ) and != ( not equal to ).

For example, x == y implies whether x is equal to y or not . This condition becomes


‘true’ when the value of x is the same as the value of y. Otherwise this condition
evaluates to ‘false’. Note that instead of a single equal sign, we use two of them
here. That is because a single equal to is understood as an assignment operator by
the C compiler.

Some other examples are


x != y (x not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)

C also contains three logical operators. They are && ( and ), || (or) and ! (not).

They correspond to the logical operations AND, OR and NOT respectively. The
NOT operator, the exclamation, is used to invert the result of any logical compare.
Using these three logical operators, we can make complex condition expressions.

5
For example,

((x < 60) || (x >= 80)) evaluates to true if x lies below 60 or if its value is 80 or
more.
((x > 0) && (x % 2 == 0) && (x % 10 != 0)) is true for all positive even integer
values of x that are not multiples of ten.
!(x > 10) is same as (x <= 10), and this expression is true for all values of x upto
(and including) 10.

Such expressions are used in conditional operators, conditional statements that use
'if' keyword, and in loops that run based on certain conditions. We will see them in
more detail later.

When a compound condition expression is evaluated, the evaluation proceeds from


left to right and as soon as the result of the outcome is assured, evaluation stops.
Thus, in the case of an AND evaluation, when one of the terms evaluates to false,
evaluation is discontinued because additional true terms cannot make the result
ever become true. For example let us check the expression we just mentioned.
((x > 0) && (x % 2 == 0) && (x % 10 != 0)) The computer does not evaluate the
second and third expressions if x is a negative integer or if x is 0.

In the case of an OR evaluation, if any of the terms is found to be true, evaluation


stops because it will be impossible for additional terms to cause the result to be
false. In the case of additionally nested terms, the above rules will be applied to
each of the nested levels.

The conditional operator

The conditional operator is a ternary operator. The conditional expression consists


of three expressions separated by a question mark and a colon. The expression
prior to the question mark is evaluated to determine if it is true or false. If it is true,
the expression between the question mark and the colon is evaluated, and if it is
not true, the expression following the colon is evaluated. The result of the
evaluation is used for the assignment if this is an assignment expression.

A conditional expression is written in the form

expression 1 ? expression 2 : expression 3

Examples:

c = (a > b ? a : b); /* c will have the maximum of a and b */

6
Here if a > b , the value of a will be assigned to c ob value of b will be assigned to c
and c will have the maximum of a and b

c = (a > b ? b : a); /* c will have the minimum of a and b */

a = (b >= 4.5 ? 8.0 : 9.5 );

Here if b >= 4.5 , c will get the value 8.0 else c will get 9.5

3. Mixing of different data types and the typecast operator

It is natural to think of an operation, like addition or multiplication, that involves one


integer and a real number. Also, since character data type also works with a
corresponding integer, we can think of mixing char and int type variables as well in
various ways. The compiler has clear-cut rules to decide on how to do such
conversions. For instance,

 An arithmetic operation between an integer and integer always yields an


integer result.
 An operation between a real (or floating point) number and another real
number always results in a real number.
 An operation between an integer and a real number always results in a real
number. In this operation the integer is first converted to a real number and
then the operation is performed. For instance, a = b + c where b is an
integer and c is a floating point number.

When storing character constants in character variables – for instance


A1 =’a’;
It is an integer equivalent of the character, called the ASCII value of the
character, that gets stored in the space allocated for the variable.

Arithmetic operations can be performed on integers, floating point


numbers as well as on characters. When we do it on characters, the
operation is done on their ASCII values. For example, a1 =’a’; followed by
a1++; results in a1 storing the ASCII value of the next character, i.e, ‘b’.

It is easy to convert an integer into a float: simply assign it the new value and the
system will do the proper conversion. For example, x = 5; (where x is a variable of

7
type float).

The other way is slightly more complicated because there may be a fractional part
that will have to be truncated or rounded off. The rule is that it gets truncated
always.

For example,

int x;
x = 7.7; assigns the value 7 to variable x since x is defined as an integer.

Typecast operator can be used if we want to explicitly specify type conversions.

The syntax is the typename in braces, as a prefix to an expression. For example,

( type name ) expression


x = (int)7.7;
y = (float)(x+5);

4 . Hierarchy of operations

While executing an arithmetic statement that has two or more operators, the
computer will get confused unless we have clear rules to decide in what order are
these operations carried out.

For instance, if we write 2*x-3, does it correspond to (2x)-(3) or 2(x-3)? Even if the
two operators are the same such a confusion could arise: 2/3/4 could mean (2/3) / 4
or 2 / (3/4).

For solving such issues, we define the precedence among operators, and
associativity rules for each operation.

Precedence order tells us that which operator gets precedence, and the
associativity tells us in what order the operations are to be carried out when one
operator appears multiple number of times in an expression. Multiplication and
division get priority over plus or minus. All these four operators are left to right
associative. Unary increment and decrement operators ++ and - - have higher
precedence, and they are right to left associative. Typecast operators have higher
precedence over multiplication and division but have lower precedence compared
to the unary operators ++ or - -. See the table for a complete list.

It is always safe to use parentheses to ensure the operations take place in the

8
order that we desire. A list of precedence and associativity of operations can be
seen on the screen.

Description Operator Associativity


Function expression () Left to Right
Array expression [] Left to Right
Structure operator -> Left to Right
Structure operator . Left to Right

Unary minus - Right to Left


Increment/Decrement ++ -- Right to Left
One’s compliment ~ Right to Left
Negation ! Right to Left
Address of & Right to Left
Value of Address * Right to Left
Type cast (type) Right to Left
Size in bytes sizeof Right to Left

Multiplication * Left to Right


Division / Left to Right
Modulus % Left to Right

Addition + Left to Right


Subtraction - Left to Right

Left shift << Left to Right


Right shift >> Left to Right

Less than < Left to Right


Less than or equal to <= Left to Right
Greater than > Left to Right
Greater than or equal to >= Left to Right

Equal to == Left to Right


Not equal to != Left to Right

Bitwise AND & Left to Right

Bitwise exclusive OR ^ Left to Right

Bitwise inclusive OR | Left to Right

Left to Right
Logical AND &&
Left to Right
Logical OR ||

9
Ternary conditional
?: Left to Right
Assignment = Right to Left
*= /= Right to Left
%= Right to Left
+= -= Right to Left
&= Right to Left
^= |= Right to Left
<<= >>= Right to Left
Comma , Left to Right

5. Library Functions In C

Library functions are procedural abstractions that carry out various commonly used
mathematical functions and calculations in C. Some library functions like scanf and
printf are used to input and output data. Library functions are usually grouped
together as object programs in separate library files. These library files are supplied
as the part of C compilers. Some library functions return a value TRUE or FALSE or
1 or 0. Some library functions perform some operation on data but do not return any
value.

A library function is invoked, or “called”, by writing the function name followed by a


list of arguments or data being passed to the function. These arguments must be
enclosed in parentheses and separated by comas. These can be constants,
variable names or expressions itself. Parentheses must be included even if there
are no arguments.

The syntax is functionname( arg1 , arg 2, arg3……) ;

There are many functions related to input output operations such as printf() ,
scanf(), getchar (), putchar() etc. There are function that perform on character
strings, and mathematical operations etc. For mathematical and special kinds of
function, suitable header files should be included in the programme

For example consider this programme

#include <stdio.h>
main()
{

1
int c, d;
c = getchar() ;
d = toupper(c);
putchar(d);
}

While run, this program accept a character from keyboard and store into c throught
the function getchar() , the function toupper() convert the stored value into upper
character and store in d: putchar() function display the value of variable d on
screen.

Summary

Let us summarize what we have learned till now. In this chapter we studied
expression and operators. There are different kinds of operators. They are binary
arithmetical operators, unary arithmetical operators, assignment operators,
relational and logical operators, conditional operators etc. Then we discussed about
how different kind of operators can be used together in an expression. Later we
understood the hierarchy or the order in which operators work when many of them
are in use simultaneously. At the end we discussed about the library functions and
their uses.

Questions

Now here are few questions for you. Please try to find out answers.

1) What are operators? Describe several types of operators used in C?


2) What are the differences between binary and unary arithmetic operations?
3) Describe the two equality relations in C and how do they differ from the other
relational operators.
4) Determine the hierarchy of operations and evaluate the following expression,
assuming that ‘i’ is an integer variable. i = 2*3/4+4/4+8-2+5/8;
5) What is meant by operators precedence? What are the relative precedence
of the arithmetic operators ?

11
6) The following program contains a run-time error. Find the error and fix it.
main()
{
int x,y;
x = 1/y;
}
7) Find out some important header files and library functions associated with
them.

References

1. B. W. Kernighan and D. M. Ritchie, The C Programming Language,


Prentice Hall India Learning Private Limited; 2 edition (1990)
2. Greg Perry, Absolute Beginners' guide to C, Sams Publishing; 2 Edition
1994

3. Yashwant Kanetkar, Let us C , Bpb Publications , 15 Edition , 2016

Link : http://www.iu.hio.no/~mark/CTutorial/CTutorial.html

You might also like