Expression & Operators in C

Unit 4. Expression & Operators


C Operators

1.Arithmetic Operators  (+,-,/,*,%)

2.Assignment Operators (=)

3.Bit-Wise Operator (&,|,^,>>,<<,~)

4.Increment and Decrement Operator (++,--)

5.Logical Operators (&&,||,!)

6.Relational Operators (>,<,>>,<<,=,!=)

7.Ternary Operator (? :)

8.Special Operator (,sizeof(),pointer *,->)

1.       Arithmetic Operators

C programming language supports almost common arithmetic operator such as +,-,* and modulus operator %. Modulus operator (%) returns the remainder of integer division calculation. The operators have precedence rules which are the same rule in math.

2.        Assignment Operators

C assignment operators are used to assign the value of a variable or expression to a variable. The syntax of assignment operators is:
var = expression;
var = var;

Each assignment operator has a priority and they are evaluated from right to left based on its priority. Here is assignment operator and its priority: =, +=, -=, *=, /=, %=

var +=expression; //means
2.var = var + expression;

3.        Bit-wise Operators

Bitwise operators interpret operands as strings of bits. Bit operations are performed on this data to get the bit strings. These bit strings are then interpreted according to data type. There are six bit operators: 
bitwise AND(&), 
bitwise OR(|), 
bitwise XOR(^), 
bitwise complement(~), 
left shift(<<),
 and right shift(>>). 

We use bitwise operators in some programming contexts because bitwise operations are faster than (+) and (-) operations and significantly faster than (*) and (/) operations

4.       Increment and decrement Operators

We can use increment operator to increase or decrease the value of variable. C increment operators support in both prefix and postfix form. Here are syntax of of increment operators:
++m; or m++; ++m; is equivalent to m=m+1 or m+=1;
--m; or m--; --m; is equivalent to m=m-1 or m-=1;
++m and m++ have the same meaning when they are use independently but behave differently when used in expressions on the right hand side of an assignment statement.
                Example:             m=5;
                                                Y=++m;
                                                Here the value of y and m would be 6
                                                m=5;
                                                y=m++;
                                                Here the value of y would be 5 and m would be 6

5.       Logical Operators

Logical operators allow us to combine relational operators or logical operators into one Boolean result. C programming language supports the 
Not (!), 
logical AND (&&), 
and logical OR (||).

6.       Relational Operators

Relational operators in C programming language are as follows: <, <=, >, >=, ==, != . They are used in Boolean conditions or expression and returns true or false.
like a>=b,a==b,a!=b

7.       Ternary Operator (Conditional Operator)

C Ternary Operator
C ternary operator is shorthand of combination of if and returns statement. Syntax of ternary operator is as follows:

(condition ) ? expression2: expression3

c=a>b?a:b  is same as

If(a>b)
{
c=a;
}
else
{
c=b;
        }
the above statement will check a is greater than b, if it is result will be b or a.

     8.       Special Operator
C supports some special operators like comma operator, sizeof() operator, pointer operators, and member selection operators (. And ->).
Comma operator (use of comma in for loop)
                for(n=1,m=10;n<=m;n++;m++)
sizeof() operator
                It is a compile time operator and when we use with an operand it number of bytes operand occupies. The operand may be number, constant or array.
                int a;
                float b;
                printf(“Size of integer:%d”,sizeof(a));
                printf(“Size of float:%d”,sizeof(b));
               
                output:
                Size of integer:2
                Size of integer:4


Expression

An expression is a combination of variables constants and operators written according to the syntax of C language.Expression is ended with the semicolon (;).
Some of the examples of expression are
a=b;
sum=a+b;
printf("hello");

Arithmetic Expression
Arithmetic expression consists of variable name , constants and arithmetic operators like +,-,/,* and the assignment operator =

Algebraic Expression

Arithmetic Expression

a x b – c
a * b – c
(m + n) (x + y)
(m + n) * (x + y)
(ab / c)
a * b / c
3x2 +2x + 1
3*x*x+2*x+1
(x / y) + c
x / y + c

Example: Area of circle
area=3.14*r*;
here in above arithmetic expression variables, constant, arithmetic operator * and assignment operator are used.
in above expression Variables and Constants together are called operands.
int a=10; 
is used to store the value in variable or constants.

Associativity of Operator
The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as associativity property of an operator.

Associativity can be of two type
Right to Left 
Left to Right

Example Right to Left
a=b=10;

Example Left to Right
c=a+b;

Evaluation of Expression
Assignment operator is used to evaluate the expression

variable=(expression);

computer evaluates the arithmetic expression and assign the value to the variable.
Assignment operator = have right to left associativity 
examples:
sum=a+b;
z=a+b/c;
x=a+b/c*d;
where computer will first evaluate the expression on right side of = and then assign the value to the variable.

Precedence of Arithmetic Operators
Each operator in C has a precedence associated with it. Arithmetic expression will be evaluated from left to right.

high priority * / %
low priority + -

but parenthesis () can effect the result of the expression as evaluation begins from the parenthesis, if it is there.

If two operators have same priority like the statement
c=a*b/d;
where  / and * have same priority, it will be evaluated left to right.



RULES FOR EVALUATION OF EXPRESSION 

·     First parenthesized( ), sub expression from left to right are evaluated.
If parenthesis are nested(( )), the evaluation begins with the innermost sub expression. 
Arithmetic expressions are evaluated from left to right using the rules of precedence. 
When Parenthesis are used, the expressions within parenthesis assume highest priority.







Input & Output Statements

Formatted Input/Output Statements
Formatted input output functions
printf( )
scanf( )


All input/output operations are carried out through function calls such as printf and scanf.
There are several functions that have input/output operation standards these are known as the standard input/output library.
Each program that uses a standard input/output function must contain the statement
#include <stdio.h>

Formatted Input
Scanf() is used to take formatted input in c programming. General form of scanf is
Scanf(“control string”,arg1,arg2,…argn);
The control string specifies the string format in which data is to be entered and the arguments arg1,arg2 … specifies the address of location.
Control stfing may contain field specification with % to ensure data type and and blank, tabs, newline
Blanks, tabs and newlines must separate the values supplied to scanf()
Example: scanf(“%d %d”,&num1,&num2);
Will read data  30 50 and assign it to num1=30 and num2-50
Here % sign indicates that a conversion specification follows and d known as datatype character indicates that number to be read is in integer mode. And & before the variable name is must as it is ‘address of’ operator. It gives the location number used by the variable in memory.
Commonly used scanf formats
Format specifiers
Code
Meaning
%c
Read a single character
%d
Read a decimal integer
%e
Read a floating point value
%f
Read a floating point value
%g
Read a floating point value
%h
Read a short integer
%i
Read a decimal, hexadecimal or octal integer
%o
Read an octal integer
%s
Read a string (Cannot read blank space in string)
%u
Read an unsigned decimal integer
%x
Read a hexadecimal integer
%[..]
Read a string of word(s)
 The input will be terminated when scanf encounters invalid mismatch of data. The data item must be separated by spaces and must match the variables receiving the input in same order.

Formatted Output
The printf() statement is used for printing results and captions. The general form of printf statement is
Printf(“control string”,arg1,arg2,…argn);
Where control string consist of three things:
1. Character
2. Format specification such as %d %c
3. Escape sequence such as \n \t
Examples: printf(“Programming in c”);
Printf(“sum=%d”,1234);

Commonly used printf formats
Code
Meaning
%c
print a single character
%d
Print a decimal integer
%e
Print a floating point value in exponent form
%f
Print a floating point value without exponent
%g
Print a floating point value eithrt e-type or f-type depending on value
%i
Print a single decimal integer
%o
Print a octal integer, without leading zero
%s
Print a string
%u
Print a unsigned decimal integer
%x
Print a hexadecimal integer, without leading 0x

Escape sequences are also used to provide formatted output with printf()


‘\a’ audible alert
‘\b’ back space
‘\f’ form feed
‘\n’ new line
‘\r’ carriage return
‘\t’ horizontal tab
‘\0’ null
‘\”’ double quote
‘\’’ single quote


Unformatted I/O Functions

Input
-To read a character
getch()
getche()
getchar()

-To read the string
gets()

Output
-To write a character
putch()
putchar()

-To write the string
puts()


getchar() reading a single character
For example
char name;
name=getchar();
will assign character to the variable name
getch() return the character that is typed
getche() return and display the character that is typed
getchar() also displays the charcter but it requires enter key

getch and getche are from conio.h
getchar is from stdio.h


putchar()  or putch() is used for writing a character to the terminal.
char ans=’y’;
putchar(ans)
will display y to the screen.

gets() is used to insert string from the keyboard
char fname[50];
gets(fname);
gets() accept string from the keyboard and it stop when enter key is hit. gets() can accept space and tabs of the string while scanf() can not accept it.
gets can read only one string at a time while scanf() can read more then one.

puts() is opposite of string function. It display the string on the screen
puts(fname); 
puts() can output only one string at a time while printf() can print multiple string.