C operators allow building expressions and performing operations in C programs. The main types of operators in C are arithmetic, assignment, logical/relational, bitwise, and others like sizeof. Arithmetic operators perform math operations like addition and subtraction. Assignment operators assign values. Logical operators allow conditional logic. Relational operators compare values. Bitwise operators work at the bit level. Precedence rules determine the order calculations are performed. Operators are used with operands and follow consistent rules in C.
2. C operators
To build an expression, operators are used with operands
like 4 + 5, Here, 4 and 5 are operands and ‘+’ is operator
C contains following group of operators –
1) Arithmetic
2) Assignment
3) Logical/Relational
4) Bitwise
5) Odds and ends
2
3. Arithmetic Operators
3
Pre increment/Decrement (++i or --i):
First increment/decrement current value by 1 and then use the
incremented/decremented value
Post increment/Decrement (i++ or i--):
First use the current value and then increment/decrement current value by 1 for next
time use
5. Assignment Operators
• Each expression contains two parts: lvalue and rvalue,
• Arithmetic operations are performed to calculate rvalue,
• Assignment operators are used to assign the rvalue to lvalue
Example:
i=i+1
can also be reduced to
i+=1
5
7. Relational Operators
7
•If condition is true it returns 1 else returns 0.
a relational operator is a programming language construct or operator that
tests or defines some kind of relation between two entities.
9. Relational Operators (Cont..)
/* C program to find largest number using if...else statement */
#include <stdio.h>
int main()
{ float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if (a>=b) {
if(a>=c)
printf("Largest number = %f",a);
else
printf("Largest number = %f",c);
}
else {
if(b>=c)
printf("Largest number = %f",b);
else
printf("Largest number = %f",c);
}
return 0;
}
9
10. Logical Operators
Allow a program to make a decision based on multiple conditions.
Each operand is considered a condition that can be evaluated to a true or false value.
Logical operator returns 0 or 1.
The Logical operators are: &&, || and !
op1 && op2-- Performs a logical AND of the two operands.
op1 || op2-- Performs a logical OR of the two operands.
!op1-- Performs a logical NOT of the operand.
Op1 and op2 may be one condition or single operand
C considers non-zero value to true and zero to false.
Examples:(a>b)&&(a>c) , a&&b, 5&&8 etc.
10
11. &&(Logical AND)
The && operator is used to determine whether both operands or
conditions are true
For example:
A=50,b=9
if (a == 10 && b == 9)
printf(“Hello!");
If either of the two conditions is false or incorrect, then the printf command is bypassed.
Ex2: if(0&&9)
printf(“Correct !”);
else
printf(“Incorrect !”);
11
13. || (Logical OR)
The || operator is used to determine whether either of the condition is true.
For example:
A=50,b=9
if (a== 10 || b == 9) // either of the condition should be true for printing hello!
printf(“Hello!");
If both of the two conditions are false, then only the printf command is bypassed.
Ex2: if(0||9)
printf(“Correct !”);
else
printf(“Incorrect !”);
Caution: If the first operand of the || operator evaluates to true, the second operand
will not be evaluated. This could be a source of bugs if you are not careful.
For instance, in the following code fragment:
if (9 || X++) {
print(“X=%dn“,X); } variable X will not be incremented because first condition is
evaluates to true.
13
14. ! (Logical NOT)
The ! operator is used to convert true values to false and false values
to true. In other words, it inverts a value
For example:
A=50,b=9
if (!(a== 10)) //
printf(“Hello!");
Ex2: if(!(0||9))
printf(“Correct !”);
else
printf(“Incorrect !”);
14
15. Bitwise Operators
15
•In the C programming language, operations can be performed
on a bit level using bitwise operators.
•Following are the bitwise Operators
16. Bitwise AND
16
•A bitwise AND takes two binary representations of equal length and performs
the logical AND operation on each pair of corresponding bits.
•The result in each position is 1 if the first bit is 1and the second bit is 1; otherwise,
the result is 0.
•Example: a=5, b=3;
• printf(“%d”,a&b); will print 1
• 0101--5
• & 0011--3
0001--1
•& operation may be used to determine whether a particular bit is set (1) or clear (0).
For example,
•given a bit pattern 0011 (decimal 3), to determine whether the second bit is set we
use a bitwise AND with a bit pattern containing 1 only in the second bit:
• 0011 (decimal 3)
• & 0010 (decimal 2)
• 0010 (decimal 2)
17. Bitwise OR(|)
17
•A bitwise OR takes two bit patterns of equal length and performs the logical
inclusive OR operation on each pair of corresponding bits.
•The result in each position is 1 if the first bit is 1 or the second bit is 1 or both bits
are 1; otherwise, the result is 0. For example: Example: a=5, b=3;
• printf(“%d”,a|b); will print 7
• 0101--5
• | 0011--3
0111--7
•A bitwise XOR(^) takes two bit patterns of equal length and performs the logical
exclusive OR operation on each pair of corresponding bits.
•The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but
will be 0 if both are 0 or both are 1.
•printf(“%d”,a^b); will print 6
• 0101--5
• ^ 0011--3
0110--6
18. shift Operator
Left Shift Operator (<<):The left shift operator will shift the bits
towards left for the given number of times.
int a=2<<1;
Printf(“%d”,a);//
If you left shift like 2<<2, then it will give the result as 8.
Therefore left shifting 1 time, is equal to multiplying the value by 2.
Right shift Operator ( >>)
The right shift operator will shift the bits towards right for the given
number of times
int b=4>>1
printf(“%d”,b);//
Right shifting 1 time, is equivalent to dividing the value by 2.
18
will print 4
will print 2
20. Odds and Ends Operators
20
There are few other important operators
including sizeof and ? : supported by C Language.
21. Examples of sizeof()
#include <stdio.h>
main() {
int a = 4;
float b=50.45;
char c;
printf("Size of variable a = %dn", sizeof(a) );
printf("Size of variable b = %dn", sizeof(b) );
printf("Size of variable c= %dn", sizeof(c) );
printf("Size of 233= %dn", sizeof(233) );
printf("Size of 20.55= %dn", sizeof(20.55) );
printf("Size of 'y'= %dn", sizeof('y') );
printf("Size of unsigned int= %dn", sizeof(unsigned int) );
}
21
22. Examples of conditional
operator(Ternary Operator)
main() {
int a , b,c;
a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %dn", b );
c = (a == 10) ? 20: 30;
printf( "Value of c is %dn", c );
}
22
23. Operators available in C can be classified in following way:
1. unary – that requires only one operand.
For example: &a, ++a, *a ,--b etc.
1. binary - that requires two operands.
For example: a + b, a * b, a<<2
1. ternary - that requires three operands.
For example: (a>b) ? a : b [ ? : ]
24. 24
Precedence and associativity
•Associativity indicates in which order two operators of same precedence
(priority) executes.
•If more than one operators are involved in an expression then, C language has
predefined rule of priority of operators. This rule of priority of operators is called
operator precedence.
25. 25
•precedence of arithmetic operators(*,%,/,+,-) is higher than
relational operators(==,!=,>,<,>=,<=) and precedence of
relational operator is higher than logical operators(&&, || and !).
Examples of precedence of operators
26. 26
a==b!=c
Here, operators == and != have same precedence.
The associativity of both == and != is left to right, i.e, the expression in left is
executed first and execution take pale towards right.
Thus, a==b!=c equivalent to :
(a==b)!=c
Ex2
Associativity is important, since it changes the meaning of an expression.
Consider the division operator with integer arithmetic, which is left associative
4 / 2 / 3 (4 / 2) / 3 2 / 3 = 0 If it were right associative, it would evaluate
to an undefined expression, since you would divide by zero
4 / 2 / 3 4 / (2 / 3) 4 / 0 = undefined
Example of Associativity of Operators
27. 27
i = 2 * 3 / 4 + 4 / 4 + 8 - 2 + 5 / 8
i = 6 / 4 + 4 / 4 + 8 - 2 + 5 / 8 operation: *
i = 1 + 4 / 4 + 8 - 2 + 5 / 8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i = 1 + 1 + 8 - 2 + 0 operation: /
i = 2 + 8 - 2 + 0 operation: +
i = 10 - 2 + 0 operation: +
i = 8 + 0 operation : -
i = 8 operation: +
What will be the value of i
28. 28
•Although Arithmetic instructions look simple to use one often commits mistakes in
writing them.
•following points should keep in mind while writing C programs:
(a)C allows only one variable on left-hand side of = That is, z =k * l is legal,
whereas k * l = z is illegal.
(b)Other than division operator(/) C has modulus operator(%).
Thus the expression 10 / 2 yields 5, whereas, 10 % 2 yields 0.
• Note that the modulus operator (%) cannot be applied on a float.
•Also note that on using % the sign of the remainder is always same as the sign of the
numerator. Thus –5 % 2 yields –1, whereas, 5 % -2 yields 1.
(c) An arithmetic instruction is often used for storing character constants in character
variables.
char a, b, d ;
a = 'F' ;
b = 'G' ;
d = '+' ;
When we do this the ASCII values of the characters are stored in the variables.
ASCII values are used to represent any character in memory. The ASCII values of
‘F’ and ‘G’ are 70 and 71.
Arithmetic expressions vs C expressions
29. 29
(d) No operator is assumed to be present. It must be written explicitly. In the
following example, the multiplication operator after b must be explicitly written.
a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) C statement
(e) Unlike other high level languages, there is no operator for performing
exponentiation operation. Thus following statements are invalid in C.
a = 3 ** 2 ;
b = 3 ^ 2 ;
If we want to do the exponentiation we have pow() function in C:
#include <math.h>
main( )
{
int a ;
a = pow ( 3, 2 ) ;
printf ( “a=%d”, a ) ;// will print 9
}
Here pow( ) function is a standard library function. It is being used to raise 3 to
the power of 2. #include <math.h> is a preprocessor directive. It is being used here
to ensure that the pow( ) function works correctly.
Arithmetic expressions vs C expressions(cont..)
32. 32
•In a C program, comma is used in two contexts: (1) A separator (2)
An Operator.
•int a=1, b=2, c=3, i=0; // commas act as separators in this line, not as
an operator
•i = (a, b); // stores b into i
•i = a, b; // stores a into i. Equivalent to (i = a), b;
•i = (a += 2, a + b); // increases a by 2, then stores a+b = 3+2 into i
•i = a += 2, a + b; // Equivalent to (i = (a += 2)), a + b;
•i = a, b, c; // Equivalent to (i=a),b,c
•i = (a, b, c); // stores c into i, discarding the unused a and b rvalues
•return a=4, b=5, c=6; // returns 6, not 4,
•return 1, 2, 3; // returns 3, not 1.
•return(1), 2, 3; // returns 3, not 1.
Comma Operator
33. printf() Function
prinf(print formatted) writes to the standard output (stdout)
a sequence of data formatted as the format argument specifies.
void main(){
int a,b;
printf(“Enter value of a and b number:n”);
scanf(“%d%d”,&a,&b);
printf(“you have entered a=%d and b=%dn”,a,b);
}
Following is format string for different format:
%[flags][width][.precision][length]specifier
On success, Printf returns the total number of
characters written is returned. On failure, a negative
number is returned
34. specifier Output Example
c Character a
d or i Signed decimal integer 392
e Scientific notation (mantissa/exponent) using e character 3.9265e+2
E Scientific notation (mantissa/exponent) using E character 3.9265E+2
f Decimal floating point 392.65
g Use the shorter of %e or %f 392.65
G Use the shorter of %E or %f 392.65
o Signed octal 610
s String of characters sample
u Unsigned decimal integer 7235
x Unsigned hexadecimal integer 7fa
X Unsigned hexadecimal integer (capital letters) 7FA
p Pointer address B800:0000
% A % followed by another % character will write % to stdout.
35. length description
h
The argument is interpreted as a short int or unsigned short int
(only applies to integer specifiers: i, d, o, u, x and X).
l
The argument is interpreted as a long int or unsigned long int for
integer specifiers (i, d, o, u, x and X), and as a wide character
or wide character string for specifiers c and s.
L
The argument is interpreted as a long double (only applies to
floating point specifiers: e, E, f, g and G).
36. 36
Precision
•The "precision" modifier is written ".number", and has slightly different meanings
for the different conversion specifiers (like d or g).
•For floating point numbers (e.g. %f), it controls the number of digits printed
after the decimal point:
•printf( "%.3f", 1.2 ); will print 1.200
•If the number provided has more precision than is given, it will round. For
example:
•printf( "%.3f", 1.2348 ); will display as 1.235
•printf( "%.3f n%.3g n%.3f n%.3g n", 100.2, 100.2, 3.1415926, 3.1415926 );
•Output:
•100.200 // %.3f, putting 3 decimal places always
•100 // %.3g, putting 3 significant figures
•3.142 // %.3f, putting 3 decimal places again
•3.14 // %.3g, putting 3 significant figures
For integers, on the other hand, the precision it controls the minimum number
of digits printed:
printf( "%.3d", 10 ); Will print the number 10 with three digits: 010
37. 37
Precision (cont…)
Finally, for strings, the precision controls the maximum length
of the string displayed:
printf( "%.5sn", "abcdefg" ); displays only "abcde“
Width:
The width field is almost the opposite of the precision field.
Precision controls the max number of characters to print, width
controls the minimum number, and has the same format as
precision, except without a decimal point:
printf( "%5sn", "abc" ); //prints abc ;two blank spaces go at the
beginning, by default.
You can combine the precision and width, if you like:
<width>.<precision>
printf( "%8.5fn", 1.234 ); prints 1.23400.
38. Flag
The flag setting controls 'characters' that are added to a string, such whether to
append 0x to a hexadecimal number, or whether to pad numbers with 0s.
The specific flag options are
•The Pound Sign: #
•Adding a # will cause a '0' to be prepended to an octal number (when using
the o conversion specifier), or a 0x to be prepended to a hexadecimal number
(when using a x conversion specifier).
•printf( "%#x", 12 ); // prints in 0xc
•Whereas printf( "%x", 12 ); //prints c
•The Zero Flag: 0
•Using 0 will force the number to be padded with 0s. This only really matters if
you use the width setting to ask for a minimal width for your number. For
example, if you write:
•printf( "%05dn", 22 ); //prints 00022
•The Plus Sign Flag: +
•The plus sign will include the sign specifier for the number:
•printf( "%+dn", 10 ); //Will print +10
39. Example
Characters: a A
Decimals: 1977 650000
Preceding with blanks: 1977
Preceding with zeros: 0000001977
Some different radixes: 100 64 144 0x64 0144
Width trick: 10
A string
#include <stdio.h>
int main( )
{
printf ("Characters: %c %c n", 'a', 65);
printf ("Decimals: %d %ldn", 1977, 650000);
printf ("Preceding with blanks: %10d n", 1977);
printf ("Preceding with zeros: %010d n", 1977);
printf ("Some different radixes: %d %x %o %#x %#o n", 100, 100, 100, 100, 100);
printf ("Width trick: %*d n", 5, 10);
printf ("%s n", "A string");
return 0;
}
40. scanf( ):
scanf( ) statement is used to read data from standard input stream
(stdin), the keyboard. The syntax is:
scanf( format string with specifiers, variable names)
The specifier list is same as that of printf( ).
Example:
void(){
char x;
int y,n;
float z;
n=scanf(“%c%d%f”, &x, &y, &z);
printf(“Returned value of scanf is =%d”,n);
}
scanf( ) returns the number of values successfully read.
41. Example
/* Calculation of simple interest */
main( )
{
int p, n ;
float r, si ;
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( “Simple Interest=%f" , si ) ;
}
Note that the ampersand (&) before the variables in the scanf( )function is a must. &
is an ‘Address of’ operator. It gives the location number used by the variable in
memory. When we say &a, we are telling scanf( ) at which emory location
should it store the value supplied by the user from the keyboard.
41
42. Example
// PROGRAM 1
#include<stdio.h>
int main(void)
{
int a = 1, 2, 3;
printf("%d", a);
return 0;
}
42
// PROGRAM 2
#include<stdio.h>
int main(void)
{
int a;
a = 1, 2, 3;
printf("%d", a);
return 0;
}
// PROGRAM 3
#include<stdio.h>
int main(void)
{
int a;
a = (1, 2, 3);
printf("%d", a);
return 0;
}
43. Escape sequences
43
Escape sequence Description
' Output the single quote (') character.
" Output the double quote (") character.
? Output the question mark (?) character.
Output the backslash () character.
a Cause an audible (bell) or visual alert.
b Move the cursor back one position on the current line.
f Move the cursor to the start of the next logical page.
n Move the cursor to the beginning of the next line.
r Move the cursor to the beginning of the current line.
t Move the cursor to the next horizontal tab position.
v Move the cursor to the next vertical tab position.
44. Example
#include <stdio.h>
int main() {
printf(“Thisn isn an testn n He said, “ How are you?
"n”);
}
Output
This
is
a
test
He said, "How are you?"
44
47. 47
Type Conversions
Implicit Type Conversion:The operands of a binary operator must have
the same type and the result is also of the same type.
Integer division:
c = 9 / 2 -- c=4 (logically wrong)
Here the operands of the division are both int and hence the result also would
be int.
For correct results, one may write
c = 9.0 / 2 -- c=4.5
In case the two operands of a binary operator are different, then the ‘lower’
type will be converted to the ‘higher’ type by the compiler. This mechanism
is called Type Conversion(Implicit Type Conversion).
int i=4 ,x;
float f=2.5;
double d=10.5;
x=i*f+d; // x will have 20
48. Type Conversion for assignment
Values can be converted by assigning one expression into the other. There are
two types:
o widening conversion
o narrowing conversion
char short int long float double long double
Assignment in forward direction is widening conversion; no data is lost in it.
Assignment in backward direction is called narrowing conversion; data loss is possible in this
case.
char a = 10;
int b, c;
float d = 2.6;
b = a; // widening conversion, no data loss
c = d; // narrowing conversion, data loss, c gets value only 2
50. Explicit conversion (Type Casting): Type casting is used to
convert the data type of an identifier to another data type
temporarily.
#inlcude <stdio.h>
int main( ) {
int a=11, b=2;
float c;
c = (float)a / b;
printf(“n%f”, c);
return 0;
}
51. Which option is correct?
Main()
{
int x=2;
printf(“%d %d”,++x,++x);
}
a.3 4
b. 4 3
c. 4 4
d. o/p may vary from complier to complier
51
d. o/p may vary from complier to complier
52. Which option is correct?
Main()
{
int x=10,y=20,z=5,a
a=x<y<z;
printf(“%d”,a);
}
a. 1
b. 0
c .error
d. none of above.
52
a.
53. Which option is correct?
Main()
{
printf(“nHey JUET”);
printf(“bbbbMP”);
printf(“rHii”);
}
a. Hey JUET
b. Hii MP
c .error
d. Hey MP
53
Ans: b. Hii MP