0% found this document useful (0 votes)
17 views55 pages

C Programming Operators Explained

The document provides an overview of operators in the C programming language, categorizing them into arithmetic, assignment, logical/relational, bitwise, and others. It explains the functionality of each operator type with examples, including pre and post increment/decrement, relational comparisons, logical operations, and bitwise manipulations. Additionally, it discusses operator precedence and associativity, highlighting common pitfalls in arithmetic expressions.

Uploaded by

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

C Programming Operators Explained

The document provides an overview of operators in the C programming language, categorizing them into arithmetic, assignment, logical/relational, bitwise, and others. It explains the functionality of each operator type with examples, including pre and post increment/decrement, relational comparisons, logical operations, and bitwise manipulations. Additionally, it discusses operator precedence and associativity, highlighting common pitfalls in arithmetic expressions.

Uploaded by

Pranav Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

OPERATORS IN C

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
Arithmetic Operators

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
3
Arithmetic operators
Example
#include<stdio.h>
void main()
{
int i=7,j=5;
printf(“%d %d %d %d \n”,i+j,i-j,i*j,i/j); 12 2 35
1
printf(“%d \n”,i%j); 2
printf(“%d %d \n”,i++,++j); 7 6
printf(“%d %d \n”,i,j); 8 6
}

4
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
Assignment Operators
Example

6
Relational Operators
a relational operator is a programming language construct or operator that
tests or defines some kind of relation between two entities.

•If condition is true it returns 1 else returns 0.


7
Relational Operators (Cont..)
#include<stdio.h>
void main()
{
int i=7,j=1, k=6;
printf(“%d \n”,i==j); 0
printf(“%d \n”,i<j); 0
printf(“%d \n”,i>j); 1
printf(“%d \n”,i<=j); 0
printf(“%d \n”,i>=j); 1
printf(“%d \n”,i!=j); 1
printf(“%d \n”, k>k); 0
printf(“%d \n”, k>=k); 1
}
8
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
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
&&(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
Example of Logical operator

Output:
12
|| (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=%d\n“,X); } variable X will not be incremented because first condition is
evaluates to true.

13
! (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
Bitwise Operators
•In the C programming language, operations can be performed
on a bit level using bitwise operators.
•Following are the bitwise Operators

15
Bitwise AND
•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)

16 0010 (decimal 2)
Bitwise OR(|)
•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:
int a=5, b=3;
printf(“%d”,a|b); //will print 7

0101 --5
| 0011 --3
0111 --7

17
Bitwise XOR(|)
•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.

EX:
int a =5 , b =3;
printf(“%d”,a^b); //will print 6

0101 --5
^ 0011 --3
0110 --6

18
Shift Operators
 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);//will print 4
 If you left shift like 2<<2, then it will give the result as 8.
 Therefore left shifting n time, is equal to multiplying the
value by 2n.
 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);//
will print 2
 Right shifting n time, is equivalent to dividing the
value by 2n.
19
Bitwise Operators Example

o/p=>Turbo C++ 4.5 o/p=>Dev C++ 5.11

5
7
2
8 8

20
Odds and Ends Operators
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 = %d\n", sizeof(a) );
printf("Size of variable b = %d\n", sizeof(b) );
printf("Size of variable c= %d\n", sizeof(c) );
printf("Size of 233= %d\n", sizeof(233) );
printf("Size of 20.55= %d\n", sizeof(20.55) );
printf("Size of 'y'= %d\n", sizeof('y') );
printf("Size of unsigned int= %d\n", sizeof(unsigned int) );
}

22
Examples of conditional
operator(Ternary Operator)
main() {
int a , b,c;
a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );
c = (a == 10) ? 20: 30;
printf( "Value of c is %d\n", c );
}

23
WAP to check even or odd
using conditional operator

#include<stdio.h>
main() {
int n;
printf("Enter number n");
scanf("%d",&n);
(n%2 == 0) ? printf("%d is even",n):
printf("%d is odd",n);
}

24
Operators available in C can be classified in
following way:

1. unary – that requires only one operand.


For example: &a, ++a, *a ,--b etc.

2. binary - that requires two operands.


For example: a + b, a * b, a<<2

3. ternary - that requires three operands.


For example: (a>b) ? a : b [ ?:]
Precedence and associativity
•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.

•Associativity indicates in which order two operators of same precedence


(priority) executes.

26
Precedence and Order of
evaluation

27
Precedence and Order of
evaluation

28
Examples of precedence of operators

•precedence of arithmetic operators(*,%,/,+,-) is higher than


relational operators(==,!=,>,<,>=,<=) and precedence of
relational operator is higher than logical operators(&&, || and !).

29
Example of Associativity of Operators
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 place 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

30
What will be the value of i
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: +

31
Arithmetic expressions vs C expressions
•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.

32
Arithmetic expressions vs C expressions
(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.

33
34 01/19/26
ASCII( American Standard Code for
Information Interchange) Values

35
Arithmetic expressions vs C expressions(cont..)
(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.
36
Arithmetic expressions vs C expressions(cont..)

37
Examples Based on Operators
Example-1
#include<stdio.h>
void main()
{
int i=1,j=1;
i=2+2*i++;
printf(“i=%d",i); i=5
printf(“\nj=%d”,2+2*j++); J=4
}
Example-2
#include<stdio.h>
void main()
{
int a=2,b=7,c=10;
c=a==b;
printf(“c=%d",c); c=0
}
38
Comma Operator
•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.

39
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=%d\n”,a,b);
}
 Following is format string for different format:
 %[flags][width][.precision][length]specifier
 On success, Printf returns the total number of
characters written. On failure, a negative
number is returned
specifier Output Example

c Character a
d or i Signed decimal integer 392
3.9265e+
e Scientific notation (mantissa/exponent) using e character
2
3.9265E+
E Scientific notation (mantissa/exponent) using E character
2
f Decimal floating point 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
B800:000
p Pointer address
0
% A % followed by another % character will write % to stdout.
length description

The argument is interpreted as a short int or unsigned short


h
int (only applies to integer specifiers: i, d, o, u, x and X).

The argument is interpreted as a long int or unsigned long int


l for integer specifiers (i, d, o, u, x and X), and as a wide
character or wide character string for specifiers c and s.

The argument is interpreted as a long double (only applies to


L
floating point specifiers: e, E, f, g and G).
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%.3f \n", 100.2, 3.1415926 );
•Output:

•100.200 // %.3f, putting 3 decimal places always


•3.142 // %.3f, putting 3 decimal places again

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

43
Precision (cont…)
Finally, for strings, the precision controls the maximum length
of the string displayed:

printf( "%.5s\n", "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( "%5s\n", "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.5f\n", 1.234 ); prints 1.23400. 44
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( "%05d\n", 22 ); //prints 00022
•The Plus Sign Flag: +
•The plus sign will include the sign specifier for the number:
•printf( "%+d\n", 10 ); //Will print +10
Example
#include <stdio.h>
int main( )
{
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 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;
}
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
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.
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 memory location should it
store the value supplied by the user from the keyboard.

48
Example
// PROGRAM 1 // PROGRAM 2 // PROGRAM 3
#include<stdio.h> #include<stdio.h>
#include<stdio.h>
int main(void)
int main(void) int main(void)
{
{ int a; {
int a = 1, 2, 3; a = 1, 2, 3; int a;
printf(“a=%d", a); a = (1, 2, 3);
printf("%d", a);
return 0; printf(“a=%d", a);
return 0; return 0;
}
} }

Compilation Error a=1 a=3

49
Escape sequences
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.

50
Example
#include <stdio.h>
int main() {
printf(“This\n is\n a\n test\n \n He said, \“
How are you?\ "\n”);
}
Output
This
is
a
test
He said, "How are you?"

51
Example
#include<stdio.h>
void main(){
char ch='a';
printf("ASCII value of %c is =
%d",ch,ch);
}
Will print:
ASCII value of a is =97

52
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

d. o/p may vary from complier to complier


53
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.
a.
54
Which option is correct?
Main()
{
printf(“\nHey JUET”);
printf(“\b\b\b\bMP”);
printf(“\rHii”);
}
a. Hey JUET
b. Hii MP
c .error
d. Hey MP
Ans: b. Hii MP
55

You might also like