Unit-2-Cprg
Unit-2-Cprg
Operators in C
An operator is a symbol that tells the computer to perform some mathematical or logical
manipulation. Operators are used in programs to manipulate data and variables.
Operators are usually a part of the mathematical or logical expressions. Generally the usage of an operator is
as shown below:
operand1 op operand2
In the above format, operand1 and operand2 can be either data or variables or expressions. Op is
the operator. In C, based on the number of operands on which an operator can operate, the
operators are divided into three types namely: unary, binary and ternary.
Unary operators work on single operand, binary operators work on two operands and ternary
operators work on three operands.
There are 8 different categories of C operators as shown below:
– Arithmetic (+, -, *, /, %)
– Relational (>, >=, <, <=, ==, !=)
– Logical (&&, ||, !)
– Assignment (=)
– Increment, Decrement (++, --)
– Conditional (? : )
– Bitwise (<<, >>, &, |, ^)
– Special (comma, sizeof, pointer)
Arithmetic Operators
C provides all the basic arithmetic operators. The arithmetic operators can operate on any built-in
data type in C. The unary minus operator multiplies its single operand with -1. Integer division
truncates any fractional part. The modulo division operator (%) produces the remainder of an
integer division. The modulo operator cannot be used on floating point values.
Relational Operators:
In C, whenever there is a need to compare two values and make a decision based on the outcome
of the comparison, we use relational operators.
For example, we can compare a person’s age with a value and based on whether the person’s age
is less than or equal or greater than the value, we may take a decision.
Logical Operators:
The relational operators are used to compare at most two values i.e. testing one condition. To test
more than one condition, we use logical operators along with relational operators.
The logical operators always evaluates to either 0 or 1 like relational operators. The logical
operators available in C and their corresponding truth tables are as shown below:
Assignment Operator:
The assignment operators are used to assign value of an expression to a variable. The general
assignment operator is = (equal). In C, there are some special assignment operators known as
shorthand operators. The syntax of shorthand operators is as shown below:
var op=expr;
In the above shown syntax, var is a variable, op is an arithmetic operator and exp can be any
expression or value or a variable. The use of shorthand operators has three advantages:
1. Easier to write.
2. The statement is more concise and easier to read.
3. The statement is more efficient.
The assignment operators in C are as shown below:
Operator Example
= a = 10
+= a+=10 (a=a+10)
-= a-=10 (a=a-10)
*= a*=10 (a=a*10)
/= a/=10 (a=a/10)
%= a%=10 (a=a%10)
Increment/Decrement Operators:
The increment and decrement operators provided by C are used to increment or decrement the
operand by a value of one. Both the increment and decrement operators are unary operators.
These operators are used extensively inside for loop and while loop.
There are two variations in how the increment and decrement operators can be used. They are as
shown below:
var++ var-- postfix
or
++var --var prefix
In the above shown syntax, var++ is known as post increment(postfix increment) and ++var is
known as pre increment (prefixincrement). Although both of them increment the variable by a
value of one, they behave differently when they are used in expressions.
In expressions, when post increment is applied, the value of the variable is used in the evaluation
of the expression and after the expression is evaluated, the value of the variable is incremented by
a value of one.
When pre increment is applied, the value of the variable is incremented by one first and then that
value is used for evaluation of the expression.
The increment and decrement operators available in C are:
Conditional Operator:
The conditional operator “? :” in C, is a ternary operator, which operates on three operands. This operator is
used to construct conditional expressions of the form:
exp1?exp2:exp3;
where exp1 is a relational expression(comparison) and is evaluated first. If TRUE, then exp2 is
evaluated or otherwise exp3 is evaluated.
For example,
a=10; b=15;
x = (a>b) ? (a-b) : (b+a);
Here, x will be evaluated to 25.
But if,
a=15; b=10;
x = (a>b) ? (a-b) : (b+a);
then, x will be evaluated to 5.
Bitwise Operators:
C supports a set of operators which operate at bit-level. These operators are known as bitwise
operators. The bitwise operators are used for testing a bit, setting a bit, complementing a bit or for
shifting the bits to left or right. The bitwise operators available in C are as shown below:
Special Operators:
C supports some special operators such as comma “,” operator, sizeof operator, address “&”
operator, pointer operator “*” and some others.
• comma operator
• sizeof operator
• pointer operators, & and *
• member selection operators, . and ->
Comma Operator: The comma “,” operator is used to combine multiple related expressions
together. A comma separated list of expressions is evaluated from left to right and the value of the
right most expression is the value of the combined expression.
For example,
value = (x=10, y=5, x+y);
gives value = 15
comma is also used for interchanging values
t=x, x=y, y=t;
Also used in for and while loop.
sizeof operator: The sizeof operator computes the size of an expression or variable or constant or
a data type. This operator is used extensively for determining the length of an array, structure or
union when the programmer does not know their actual sizes.
The sizeof operator is also used in dynamic memory allocation. The general syntax
of sizeof operator is as shown below:
var = sizeof(operand);
where the operand can be either a value or variable or data type or an expression
For example,
int sum;
m = sizeof(sum);
y = sizeof(short int);
k = sizeof(67L);
It is a compile time operator.
Arithmetic Expression:
An expression is a sequence of operands and operators that reduces to a single value. For example,
the expression, 10+5 reduces to the value of 15.
Based on the operands(variables or constants) and operators used in the expression, they are
divided into several types. Some of them are:
1. Integer expressions – expressions which contains integers and operators
2. Real expressions – expressions which contains floating point values and operators
3. Arithmetic expressions – expressions which contain operands and arithmetic operators
4. Mixed mode arithmetic expressions – expressions which contain both integer and real
operands
5. Relational expressions – expressions which contain relational operators and operands
6. Logical expressions – expressions which contain logical operators and operands
7. Assignment expressions and so on… – expressions which contain assignment operators and
operands
Examples of some expressions in C are
Expression Evaluation:
The general form of an expression in C is as follows:
var = expression;
When above statement is encountered, first the expression on the right hand side is evaluated,
and then the result is assigned to the variable on the left hand side. For example,
x = a*b-c;
z = a – b / c + d;
Expressions are evaluated based on operator precedence and associativity rules when an
expression contains more than one operator.
If statement:
This is a decision making statement used with an expression. The expression will be a comparision
operation, using relational operators. Based on the evaluation of the test expression, which will
either result in a TRUE(1) or a FALSE(0) value, some statements will be executed, or will be
skipped. The general form of the if statement is as shown below:
if (test-expression)
Some examples
1. if (bank balance is zero)
borrow money
2. if (room is dark)
put on lights
3. if (code is 1)
person is male
4. if (age is more than 55)
person is retired
The different form of the if statement are:
1. Simple if statement
2. if …… else statement
3. Nested if …. else statement
4. else if ladder
if(category==‘S’)
{
marks = marks+bonus_marks;
}
printf(“%d”, marks);
Write a C program to read percentage of marks, and print result “PASS” if percentage > or
equal to 40 or “FAIL” if percentage <40.
/*prg to print result*/
#include<stdio.h>
float percent;
main()
{
printf(“enter the percentage”);
scanf(“%f”,&percent);
if(percent>=40.0)
printf(“Pass”);
if(percent<40.0)
printf(“Fail”);
}
Nested if statement:
This branching statement is used when a series of decisions are involved. Nested means one inside
the other. This is also called as cascaded if statement.
If the condition is evaluated to true in the first if statement, then the condition in the
second if statement is evaluated and so on.
The flowchart and the syntax for the nested if statement is shown below.
Syntax: Flowchart:
if (test condition1)
{
if (test condition2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
An example of the nested if statement is explained below.
Bank announces bonus policy. A bonus of 2% of the balance is given to everyone, for any amount
of balance. A bonus of 5% is given to female account holders if balance if greater than Rs. 5000.
if (sex is female)
{
if (balance>5000)
bonus = .05*balance;
else
bonus = .02*balance;
}
else
{
bonus = 0.02*balance;
}
balance = balance + bonus;
The problem with the nested if.. else statement and the else.. if ladder is that the implementation
becomes complex. The more the alternatives, the more complex it becomes, sometimes even the
person who has implemented it also becomes confused.
In order to make it easier to implement multi-conditional branching, C language has the switch
statement.
switch(expression)
{
case label1 : statement(s);
break;
case label2 : statement(s);
break;
case label3 : statement(s);
break;
.
.
.
default: statement(s);
break;
}
The switch statement switches between the blocks based on the value of the expression. Each
block will have a value associated with it. Each block is represented using the case keyword and
the case keyword follows with the label of the block. Every block ends with a break statement.
In a switch statement, both the default block and the break statement are optional. If none of
the blocks are matched, then the statements in the default block are executed. If we remove
the break statement from a particular block, all the subsequent blocks are also executed until
the next break statement is encountered.
Rules for the switch statement are as follows:
• The switch expression must be of an integer or character type.
• The case value must be an integer or character constant.
• The case value can be used only inside the switch statement.
• The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known
as fall through the state of C switch statement.
• default label is optional. It will be executed if none of the case values match.
• Only one default is allowed. And it can be placed anywhere.
• Nesting of switch statements is allowed.
A sample program is shown below:
/*program to read marks in 6 subjects(100 marks each), calculate percentage(average) and print
result(class secured) */
#include<stdio.h>
float m1, m2, m3, m4, m5, m6;
int total, average;
main()
{
printf(“Enter marks in 6 subjects:”);
scanf(“%f%f%f%f%f%f”, &m1, &m2, &m3, &m4, &m5, &m6);
total = m1+m2+m3+m4+m5+m6;
average = total/6;
switch(average/10)
{
case 0 : ;
case 1 : ;
case 2 : ;
case 3 : printf(“Fail”);
break;
case 4 : printf(“Pass”);
break;
case 5 : printf(“Second Class”);
break;
case 6 : printf(“First Class”);
break;
case 7 : ;
case 8 : ;
case 9 : printf(“Distinction”);
break;
}
}
Conditional Operator:
For conditional expressions, a ternary operator (3 operands), is used as follows
where exp1, exp2 and exp3 are expressions. exp1 is a relational expression(comparison) and is
evaluated first. If TRUE, then exp2 is evaluated or otherwise exp3 is evaluated. For eg.
a=10; b=15;
goto statement:
All branching statements seen so far are based on some condition. The goto statement is an
unconditional branching statement.
A label has to be used with the goto statement. A label can be defined by using a name(should not be a
keyword or a variable) followed by a : (colon). Any label should be followed by a C language statement
which ends with a ; (semi-colon). The goto statement should refer to the label.
goto label;
label: statement(s);
Loop means a sequence of statements are executed repeatedly till some condition is satisfied.
while(test condition)
• Then test condition is evaluated again, if found true, the body of the
loop is repeated until the test condition becomes false
do
body of loop
} while(test-condition);
• The body of the do…while loop is executed first and then the
condition is evaluated.
• If the value is false, the execution of the body of the loop stops.
body of loop
• If the value of the condition is true, the body of the for loop is executed. Otherwise, the body of the
loop is not executed.
• After the execution of the for loop’s body, the counter is either incremented or decremented. Then
the condition is evaluated again and so on.
The following two programs illustrate how the different loop statements can be used.