UNIT 2
OPERATORS IN C
There are 8 operators in C:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Conditional operators
6. Increment and Decrement operators
7. Bitwise operators
8. Special operators
1. Arithmetic operators:
Used for: It is used for arithmetic calculations like addition, subtraction,
multiplication, division etc.
List of operators: +, -, *, /, % (modulus or mod operator)
Syntax: exp op exp
eg: 5+2
a+b
(a+b)*(c/2)
These are binary operators i.e. they require two operands
When both operands are integer the result is integer.
When both operands are float the result is float.
If one operand is integer and other is float the result is float.
/ operator always gives quotient when both operands are integer.
Modulus operator % gives the remainder
Modulus operator % can only be applied to integer operands.
Modulus operator % always takes the sign of the first operand as sign of the result.
2. Relational operators
Used for: Comparing two or more values
List of operators:
< less than
<= less than equal to
> greater than
>= greater than equal to
== is equal to
!= not equal to
Syntax: exp op exp
Eg: a>b
5<2
(a+b)<500
These are binary operators i.e require two operands
They always evaluate to true or false i.e. 1 or
0 eg: printf(“%d”, 5<2);
3. Logical Operators
Used for: Combining two or more relational expressions to reach a particular decision
List of operators:
&& logical AND binary operators
|| logical OR
! logical NOT unary operator
Syntax: exp op exp ( for && and ||)
!exp (for !)
eg: (a>b) && (a>c)
(5>3) && (1<2)
1&&2
Logical AND and Logical OR are binary operators, whereas Logical NOT is a
unary operator
These operators also evaluate to either true or false i.e.1 or 0
4. Assignment operator
= is called the assignment operator
It is used to assign value to variables
Syntax: variable=exp
eg: c=a
x=5
z=(a>b)+(5*b)
It is a binary operator
Stores the value of the expression on R.H.S. to the variable on L.H.S
Shorthand representation can be done
like: If a=a+1 then it can be written as
a+=1
5. Increment and Decrement Operator
++ is increment operator
-- is decrement operator
Increment operator (++) is used to add 1 to the variable
Decrement operator (--) is used to subtract 1 from the variable
Syntax: ++variable if applied prefix variable++ if applied postfix
--variable variable- -
eg: ++a (prefix increment)
--a (prefix decrement)
a++ (postfix increment)
a-- (postfix decrement)
These are unary operators i.e. Require single operand
They can be applied only on integer variables
They can be applied prefix or postfix.
Increment always adds 1 to the variable and decrement always subtracts 1 from
the variable
Q. What is the difference between prefix and postfix increment and decrement operators?
Ans:
1. When prefix increment or decrement operator is applied to a variable in an expression,
its value is incremented or decremented first and then it is used in the expression.
2. When postfix increment or decrement operator is applied to a variable in an
expression, its value is used first in the expression and then it is incremented or
decremented.
Eg:
int x=5, y=4, z;
z=x++; z=5 x=6
z=--y; z=3 y=3
z=--x; z=5 x=5
z=y++;z=3 y=4
printf(“%d\t%d\t%d”,x,y,z); 5 4 3
6. Conditional operators
It is a ternary operator
The conditional operator is ?:
Used for decision based problems ( if –then-else)
Syntax: exp1 ? exp2 : exp
3 where
exp1 is the condition
exp2 is executed when condition becomes true (then part)
exp3 is executed when the condition becomes false ( else part
Eg:
(a>=b)? printf(“%d is larger”,a):printf(“%d is larger”,b);
c= (a>=b)?a:b;
7. Bitwise operators
C has a collection of bitwise operators for manipulation of data at bit level
These operators are used for testing the bits, performing AND operation at bit
level, performing OR operation at bit level, shifting them right or left etc.
These operators can only be applied on integer variables.
List of operators:
& bitwise AND
| bitwise OR
^ bitwiseXOR(AB’+A’B)
<< bitwise shift left
>> bitwise shift right
~ bitwise complement unary operator
Eg:
W. A.P to illustrate the use of bitwise operators
/* bitwise operators */
void main()
{
int a=11, b=9, /* a=00001011, b=00001001 */
c; c=a&b;
printf(“%d”,c); /*c=00001001 =9 */
c=a|b;
printf(“%d”,c); /*c=00001011=11*/
c=a^b;
printf(“%d”,c); /*c=00000010=2 */
c=a<<2;
printf(“%d”,c); /*c=00101100= 44 */
c=b>>2;
printf(“%d”,c); /*c=00000010 =2*/
c=~a;
printf(“%d”,c); /*c= 11110101=-12*/
getch();
}
8. Special Operators
List of operators: sizeof() operator, comma (,) operator and pointer operators( &, *)
sizeof() operator -when used with an operand return the number of bytes occupied by the
operand in computer’s memory. The operand can be a data type, a variable or a constant value.
eg:
char a;
c=sizeof(int); 2
c=sizeof(5.4); 4
c=sizeof(a); 1
comma (,) operator – evaluates the list of expression from left to right and the value of the
rightmost expression becomes the value of the combined expression.
Eg: c= a=5,b=6,a+b;
& and * are pointer operators.
Precedence and Associativity of operators-
Precedence- Precedence of operators gives the priority of operators i.e tells which operator
should be evaluated first in an expression.
Associativity- Associativity gives the order of evaluation when there are different operators of
same precedence in the expression i.e. tells the order in which to evaluate a expression either
left to right or right to left
Operator Precedence Associativity
() 1 Left to right
++, --, ! 2 Right to left
*, /, % 3 Left to right
+, - 4 Left to right
<,<=,>,>= 5 Left to right
==, != 6 Left to right
&& 7 Left to right
|| 8 Left to right
?: 9 Left to right
Some examples:
Solve the following
expressions: 1. X=
2*3/4+4/4+8-2+5/8
2. K=3/2*4+3/8+3
3. K=9-12/3+3*2-1
4. K=9-12/(3+3)*(2-1)
5. K=9-(12/(3+3)*2)-1
6. K=9-((12/3)+3*2)-1
Solutions:
1. X=2*3/4+4/4+8-2+5/8
X= 6/4+4/4+8-2+5/8
X=1+4/4+8-2+5/8
X=1+1+8-2+5/8
X=1+1+8-2+0
X=2+8-2+0
X=10-2+0
X=8+0
X=8
2. K=3/2*4+3/8+3
K=1*4+3/8+3
K=4+3/8+3
K=4+0+3
K=4+3
K=7
3. K=9-12/3+3*2-1
K=9-4+3*2-1
K=9-4+6-1
K=5+6-1
K=11-1
K=10
4. K=9-12/(3+3)*(2-1)
K=9-12/(6)*(2-1)
K=9-12/6*(1)
K=9-2*1
K=9-2
K=7
5. K=9-(12/(3+3)*2)-1
K=9-(12/(6)*2)-1
K=9-(2*2)-1
K=9-4-1
K=5-1
K=4
6. K=9-((12/3) +3*2)-1
K=9-(4+3*2)-1
K=9-(4+6)-1
K=9-10-1
K=-1-1
K=-2
Q What is Typecasting?
Ans: Typecasting is a way to convert a variable from one datatype to another data type. This is
also called explicit type conversion.
Syntax: (datatype)variable;
eg: int sum; float avg; avg=(float)sum/5.0;
Q. What is type conversion in C? What is Type casting? Differentiate between explicit
and implicit type conversion?
Ans: Type conversion – is the conversion of a variable of one datatype to another for
evaluation of a particular expression. It is of two types:
1. Implicit Type conversion or automatic type conversion
2. Explicit type conversion or Type casting
Implicit Type conversion Explicit Type conversion
1. The type conversion that is done by The type conversion that is done by the
the compiler itself is called implicit user deliberately is called explicit type
or automatic type conversion conversion or typecasting
2. float avg ; float avg ;
int sum ;
int sum , n
avg = sum /25.0 ;
;
avg = (float )sum / n ;
In the above example, since sum is divided In the above example, sum has been
with 25.0 which is a floating point typecasted to float , so that when the
number, the compiler promotes sum to expression is evaluated we get the
float and then evaluates the expression.
This kind of automatic conversion, done correct result.
by the compiler itself is called implicit.
Try the following programs:
1. W.A.P. to convert temperature from degree Celsius to degree Fahrenheit
2. W.A.P to find simple and compound interest.
C Type Conversion
In C programming, we can convert the value of one data type
(int, float, double, etc.) to another. This process is known as type
conversion. Let's see an example,
#include <stdio.h>
int main() {
int number = 34.78;
printf("%d", number);
return 0;
}
// Output: 34
Run Code
Here, we are assigning the double value 34.78 to the integer variable number.
In this case, the double value is automatically converted to integer value 34.
This type of conversion is known as implicit type conversion. In C, there are
two types of type conversion:
1. Implicit Conversion
2. Explicit Conversion
Implicit Type Conversion In C
As mentioned earlier, in implicit type conversion, the value of one type is
automatically converted to the value of another type. For example,
All the data types of the variables are upgraded to
the data type of the variable with largest data type.
char -> int-> long int -> float -> double -> long double
#include<stdio.h>
int main() {
// create a double variable
double value = 4150.12;
printf("Double Value: %.2lf\n", value);
// convert double value to integer
int number = value;
printf("Integer Value: %d", number);
return 0;
}
Run Code
Output
Double Value: 4150.12
Integer Value: 4150
The above example has a double variable with a value 4150.12. Notice that
we have assigned the double value to an integer variable.
int number = value;
Here, the C compiler automatically converts the double value 4150.12 to
integer value 4150.
Since the conversion is happening automatically, this type of conversion is
called implicit type conversion.
Example: 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;
}
Run Code
Output
Character Value: a
Integer Value: 97
The code above has created a character variable alphabet with the value 'a'.
Notice that we are assigning alphabet to an integer variable.
int number = alphabet;
Here, the C compiler automatically converts the character 'a' to integer 97.
This is because, in C programming, characters are internally stored as integer
values known as ASCII Values.
ASCII defines a set of characters for encoding text in computers. In ASCII
code, the character 'a' has integer value 97, that's why the character 'a' is
automatically converted to integer 97.
If you want to learn more about finding ASCII values, visit find ASCII value of
characters in C.
Explicit Type Conversion In C
In explicit type conversion, we manually convert values of one data type to
another type. For example,
#include<stdio.h>
int main() {
// create an integer variable
int number = 35;
printf("Integer Value: %d\n", number);
// explicit type conversion
double value = (double) number;
printf("Double Value: %.2lf", value);
return 0;
}
Run Code
Output
Integer Value: 35
Double Value: 35.00
We have created an integer variable named number with the value 35 in the
above program. Notice the code,
// explicit type conversion
double value = (double) number;
Here,
(double) - represents the data type to which number is to be converted
number - value that is to be converted to double type
Example: Explicit Type Conversion
#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;
}
Run Code
Output
Integer Value: 97
Character Value: a
We have created a variable number with the value 97 in the code above. Notice
that we are converting this integer to character.
char alphabet = (char) number;
Here,
(char) - explicitly converts number into character
number - value that is to be converted to char type
1. Type Casting:
In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing
casting, the destination data type may be smaller than the source data type
when converting the data type to another data type, that’s why it is also called
narrowing conversion.
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
(): is a casting operator.
target_datatype: is a data type in which we want to convert the source data
type.
Type Casting example –
float x;
byte y;
...
...
y=(byte)x; //Line 5
In Line 5: you can see that, we are converting float(source) data
type into byte(target) data type.
2. Type conversion :
In type conversion, a data type is automatically converted into another data type
by a compiler at the compiler time. In type conversion, the destination data type
cannot be smaller than the source data type, that’s why it is also called widening
conversion. One more important thing is that it can only be applied to compatible
data types.
Type Conversion example –
int x=30;
float y;
y=x; // y==30.000000.
UNIT 2
DECISION CONTROL STATEMENTS
If statement
There are certain situations where the flow of control of the program is based on a decision. In
such situation decision control structures can be used.
In C, we have the following decision control structures:
1. if statement
2. switch-case-default
3. goto
4. conditional operator
if statement-
if-else
if
nested if-else
else if ladder
if-else
Syntax: if(condition)
{
block of statements;
}
else
{
block of statements;
}
Try the following programs:
1. W.A.P to find larger among two numbers
2. W.A.P to find whether a number is even or odd
3. W.A.P to find whether a number is positive OR negative.
4. W.A.P to print gross salary of an employee if basic>8000, DA=20%,
HRA=40% otherwise DA=10% and HRA=20%
5. W.A.P to find largest among three numbers
6. W.A.P to find percentage of a student and print his grade
If percentage>90 print grade A
If percentage is between 70 and 90 print grade B
If percentage is between 40 and 70 print grade C
Otherwise print Grade
D
7. W.A.P to find whether a year is leap year or not.
8. W.A.P to enter an alphabet and find whether it is uppercase or lowercase
9. W.A.P to enter an alphabet and find whether it is uppercase or lowercase and change
its case also.
10. W.A.P to find roots of a quadratic equation
Programs of conditional operators:
11. W.A.P to find largest among three numbers using conditional operator
12. W.A.P to find whether a year is leap year or not using conditional operator
1. W.A.P to find larger among two numbers
/*larger among two numbers*/
#include<stdio.h> #include<conio.h>
void main( )
{
int a, b; clrscr( );
printf(“Enter two numbers \n”);
scanf(“%d%d”,&a,&b); if(a>=b)
printf(“%d is larger”,a); else
printf(“%d is larger”,b); getch(
);
}
2. W.A.P to find whether a number is even or odd
/*larger among two numbers*/
#include<stdio.h> #include<conio.h>
void main( )
{
int num; if(num
%2= =0)
printf(“Number is even”);
else
printf(“Number is odd”);
getch( );
}
3. W.A.P to find whether a number is positive, negative or zero.
/* positive or negative
*/ #include<stdio.h>
#include<conio.h>
void main( )
{
int num; clrscr(
);
printf(“enter a number\n”);
scanf(“%d”,&num); if(num = =0)
printf(“Number is zero”); else
if(num>0)
printf(“number is positive”); else
printf(“number is negative”); getch( );
}
4. W.A.P to print gross salary of an employee if basic>8000, DA=20%,
HRA=40% otherwise DA=10% and HRA=20%
/*gross salary*/
#include<stdio.h>
#include<conio.h> void main(
)
{
float b, da, hra,
gs; clrscr( );
printf(“Enter your basic salary\n”);
scanf(“%f”,&b);
if(b>8000)
{
da=20*b/100;
hra=40*b/100;
}
else
{
da=10*b/100;
hra=20*b/100;
}
gs=b+da+hra;
printf(“Gross salary=%f”,gs); getch( );
}
5. W.A.P to find largest among three numbers
/*largest among three numbers*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c;
clrscr();
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if((a= =b) &&(a= =c))
printf(“all are equal numbers\n”); else
if((a>=b)&&(a>=c)) printf(“%d is
largest”,a);
else if((b>=a)&&(b>=c))
printf(“%d is largest”,b); else
printf(“%d is largest”,c); getch(
);
}
6. W.A.P to find percentage of a student and print his
grade If percentage>90 print grade A
If percentage is between 70 and 90 print grade B
If percentage is between 40 and 70 print grade C
Otherwise print Grade D
/*percentage of a student */
#include<stdio.h>
#include<conio.h>
void main( )
{
float a,b,c,d,e,p;
clrscr( );
printf(“ Enter marks in five subjects\n”);
scanf(“%f%f%f%f%f”, &a,&b,&c,&d,&e);
p= (a+b+c+d+e)/500*100;
if(p>90)
printf(“Grade A\n”);
else if((p>=70)&&(p<=90))
printf(“Grade B\n”);
else if((p>=40)&&(p<70))
printf(“Grade C\n”);
else
printf(“Grade D\n”);
getch( );
}
7. W.A.P to find whether a year is leap year or not
/*leap year*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int y;
clrscr( );
printf(“Enter a year\n”);
scanf(“%d”,&y);
if(y%100= =0) /*century year*/
{
if( y %400 ==0)
printf(“Leap year”);
else
printf(“not a leap year”);
else /*non century year*/
{
If(y%4==0)
printf(“Leap year”);
else
printf(“not a leap year”);
}
getch( );
}
8. W.A.P to enter an alphabet and find whether it is uppercase or lowercase
/*uppercase or lowercase*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main( )
{
char ch; clrscr( );
printf( “ Enter an alphabet \n”);
scanf(“%c”,&ch);
if ( (ch>=65) && (ch<=90) printf(“
Uppercase”);
else if ( (ch>=97) && (ch<=122) printf(“
Lowercase”);
else
printf(“ Not an alphabet “);
}
9. W.A.P to enter an alphabet and find whether it is uppercase or lowercase and change
the case of the alphabet
/*uppercase or lowercase and change the case
*/ #include<stdio.h>
#include<conio.h>
#include<math.h>
void main( )
{
char ch; clrscr( );
printf( “ Enter an alphabet \n”);
scanf(“%c”,&ch);
if ( (ch>=65) && (ch<=90)
{
printf(“ Uppercase”); ch = ch +
32;
printf(“ %c”, ch);
}
else if ( (ch>=97) && (ch<=122)
{
printf(“ Lowercase”); ch = ch -
32;
printf(“ %c”, ch);
}
else
printf(“ Not an alphabet “);
}
10. W.A.P to find roots of a quadratic equation
/*roots of quadratic
equation*/ #include<stdio.h>
#include<conio.h>
#include<math.h>
void main( )
{
float a,b,c,r1,r2,x; clrscr( );
printf(“enter coefficients a,b,c\n”);
scanf(“%f%f%f”,&a,&b,&c); if(a= =0)
printf(“not a quadratic equation”); else
{
x=(b*b)-(4*a*c);
if(x= =0)
{
r1= -b/(2*a);
printf(“Equal roots=%f”,r1);
}
else if(x<0)
printf(“Imaginary roots”);
else
{
r1=(-b+sqrt(x))/(2*a);
r2=(-b-sqrt(x))/(2*a);
printf(“Real roots are r1=%f\n r2=%f”,r1,r2);
}
}
getch( );
}
Q. Can conditional operators substitute if else. Justify
Ans: Conditional operators can substitute if-else provided:
1. Each if has else, as conditional operator is a ternary operator and hence requires
three operands
2. The block of if and else has single statements within it.
Programs of conditional operators:
11. W.A.P to find largest among three numbers using conditional operator
/ * largest among three numbers using conditional operators */ #include<stdio.h>
#include<conio.h> void main(
)
{
int a, b, c;
clrscr( ) ;
printf(“ Enter three numbers\n”);
scanf(“%d%d%d”, &a, &b, &c);
((a= =b) && (a= =c)) ? printf(“ all are equal”) : ((a>=b) && (a>=c))
? printf(“%d is largest”, a) : ((b>=a) && (b>=c)) ? printf(“ %d is largest”, b)
: printf(“ %d is largest”,
b); getch( );
}
12. W.A.P to find whether a year is leap year or not using conditional operator
/* leap year or not using conditional operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
int y; clrscr(
);
printf(“ Enter a year \n”);
scanf(“%d”, &y);
((y%100= = 0&&y%400 = = 0)||((y%100!=0 && y%4= =0))? printf (“ Leap year”) : printf( “
Not a leap year”);
getch( );
}