Unit 2
Unit 2
Operators can be defined as the symbols that help us to perform specific mathematical,
relational, bitwise, conditional, or logical computations on operands. In other words, we can
say that an operator operates the operands. For example, ‘+’ is an operator used for addition, as
shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. The functionality of
the C programming language is incomplete without the use of operators.
Types of Operators in C
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators
Operators in C
1. Arithmetic Operations in C
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example:
Increment(++) and Decrement(–) Operators
int val = 5;
cout<<++val; // 6
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example:
Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators in C
These are used for the comparison of the values of two operands. For example, checking if one
operand is equal to the other operand or not, whether an operand is greater than the other
operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for more
reference).
int a = 3;
int b = 5;
cout<<(a < b);
// operator to check if a is smaller than b
3. Logical Operator in C
Logical Operators are used to combining two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.
For example, the logical AND represented as the ‘&&’ operator in C returns true when both
the conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b
returns true when both a and b are true (i.e. non-zero)(See this article for more reference).
cout<<((4 != 5) && (4 < 5)); // true
4. Bitwise Operators in C
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.
7. Let’s look at the truth table of the bitwise operators.
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
X Y X&Y X|Y X^Y
return 0;
}
Output
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b<<1 = 18
b>>1 = 4me Complexity: O(1)
Auxiliary Space: O(1)
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing. For example, the bitwise AND operator represented as ‘&’
in C takes two numbers as operands and does AND on every bit of two numbers.
The result of AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
a) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right
to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
b) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value
on the right from the current value of the variable on left and then assigns the result to the
variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result to the
variable on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators
Apart from the above operators, there are some other operators available in C used to perform
some specific tasks. Some of them are discussed here:
i. sizeof operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable.
To know more about the topic refer to this article.
ii. Comma Operator
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator.
To know more about the topic refer to this article.
iii. Conditional Operator
The conditional operator is of the form Expression1? Expression2: Expression3
Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of Expression3.
We may replace the use of if..else statements with conditional operators.
To know more about the topic refer to this article.
iv. dot (.) and arrow (->) Operators
Member operators are used to referencing individual members of classes, structures, and
unions.
The dot operator is applied to the actual object.
The arrow operator is used with a pointer to an object.
to know more about dot operators refer to this article and to know more about arrow(->)
operators refer to this article.
v. Cast Operator
Casting operators convert one data type to another. For example, int(2.2000) would return 2.
A cast is a special operator that forces one data type to be converted into another.
The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].
To know more about the topic refer to this article.
vi. &,* Operator
Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
To determine the meaning and value of an expression in an unambiguous manner, we apply the
operator precedence and associativity rules. Arithmetic expressions without parentheses are
evaluated from left to right using the rules of operator precedence. In C, arithmetic operators
have two different priority levels.
Hight priority
*/%
Low priority
+-
The basic procedure for evaluating an expression includes two passes from left to right. The high
priority operators are applied during the first pass and the low priority operators are applied in
the second pass.
First pass
x = 8 - 5 + 2 * 5 -7
x = 8 - 5 + 10 - 7
Second pass
x = 3 + 10 - 7
x = 13 - 7
x=6
These steps are illustrated in the following figure.
However, parentheses can be used to change the order in which an expression is evaluated. The
expression within parentheses assumes the highest priority. The following rules are used for
evaluating expressions containing parentheses.
First pass
x = 8 - 14 / 7 * (8 -7)
x = 8 - 14 / 7 * 1
Second pass
x=8-2*1
x=8-2
Third pass
x=6
Typecasting in C
Typecasting is converting one data type into another one. It is also called as data conversion or
type conversion in C language. It is one of the important concepts introduced in ‘C’
programming.
Implicit type conversion in C happens automatically when a value is copied to its compatible
data type. During conversion, strict rules for type conversion are applied. If the operands are of
two different data types, then an operand having lower data type is automatically converted into
a higher data type. This type of type conversion can be seen in the following example.
#include<stdio.h>
int main(){
short a=10; //initializing variable of short data type
int b; //declaring int variable
b=a; //implicit type casting
printf("%d\n",a);
printf("%d\n",b);
}
Output:
10
10
1. In the given example, we have declared a variable of short data type with value initialized
as 10.
2. On the second line, we have declared a variable of an int data type.
3. On the third line, we have assigned the value of variable s to the variable a. On third line
implicit type conversion is performed as the value from variable s which is of short data
type is copied into the variable a which is of an int data type.
#include <stdio.h>
main() {
int number = 1;
char character = 'k'; /*ASCII value is 107 */
int sum;
sum = number + character;
printf("Value of sum : %d\n", sum );
}
Output:
#include <stdio.h>
main() {
int num = 13;
char c = 'k'; /* ASCII value is 107 */
float sum;
sum = num + c;
printf("sum = %f\n", sum );}
Output:
sum = 120.000000
First of all, the c variable gets converted to integer, but the compiler converts num and c into
“float” and adds them to produce a ‘float’ result.
Implicit type of type conversion is also called as standard type conversion. We do not
require any keyword or special statements in implicit type casting.
Converting from smaller data type into larger data type is also called as type promotion.
In the above example, we can also say that the value of s is promoted to type integer.
The implicit type conversion always happens with the compatible data types.
We cannot perform implicit type casting on the data types which are not compatible with each
other such as:
1. Converting float to an int will truncate the fraction part hence losing the meaning of the
value.
2. Converting double to float will round up the digits.
3. Converting long int to int will cause dropping of excess high order bits.
In all the above cases, when we convert the data types, the value will lose its meaning.
Generally, the loss of meaning of the value is warned by the compiler.
To force the type conversion in such situations, we use explicit type casting.
It requires a type casting operator. The general syntax for type casting operations is as follows:
(type-name) expression
Here,
#include<stdio.h>
int main()
{
float a = 1.2;
//int b = a; //Compiler will throw an error for this
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n",b);
return 0;
}
Output:
Value of a is 1.200000
Value of b is 2
1. We have initialized a variable ‘a’ of type float.
2. Next, we have another variable ‘b’ of integer data type. Since the variable ‘a’ and ‘b’ are
of different data types, ‘C’ won’t allow the use of such expression and it will raise an
error. In some versions of ‘C,’ the expression will be evaluated but the result will not be
desired.
3. To avoid such situations, we have typecast the variable ‘a’ of type float. By using explicit
type casting methods, we have successfully converted float into data type integer.
4. We have printed value of ‘a’ which is still a float
5. After typecasting, the result will always be an integer ‘b.’
Summary
Control Statements in C
In simple words, Control statements in C help the computer execute a certain logical statement
and decide whether to enable the control of the flow through a certain set of statements or not.
Also, it is used to direct the execution of statements under certain conditions.
https://www.scholarhat.com/tutorial/c/if-else-statements-in-c
Simple if statement
If-else statements
Nested if-else statements
else-if ladder
Simple if Statement
Simple if statements are carried out to perform some operation when the condition is only true. If
the condition of the if statement is true then the statements under the if block is executed else the
control is transferred to the statements outside the if block.
Flow Chart:
Example:
Output:
If-else Statement
In some situations, you may have to execute statements based on true or false under certain
conditions, therefore; you use if-else statements. If the condition is true, then if block will be
executed otherwise the else block is executed.
Flow Chart:
Example:
Output:
The nested if-else statements consist of another if or else. Therefore; if the condition of “if” is
true (i.e., an outer if) then outer if’s if block is executed which contains another if (that is inner
if) and if the condition of if block is true, statements under if block will be executed else the
statements of inner if’s “else” block will be executed.
If the outer “if” condition is not true then the outer if’s “else” block is executed which consists of
another if. The outer else’s inner if the condition is true then the statement under outer else’s
inner if is executed else the outer else’s else block is executed.
Output:
Else-if Ladder Statements
The else-if ladder statements contain multiple else-if, when either of the condition is true the
statements under that particular “if” will be executed otherwise the statements under the else
block will be executed.
Suppose the “if” condition is true, statements under “if” will be executed else the other “if”
condition is tested, and if that condition is true statements under that particular “if” will be
executed. This process will repeat as long as the else-if’s are present in the program.
Example:
Output:
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a
certain condition), it executes the statements associated with it. Basically, it is used to perform
different actions based on different conditions(cases).
Switch case statements follow a selection-control mechanism and allow a value to change
control of execution.
They are a substitute for long if statements that compare a variable to several integral values.
The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
In C, the switch case statement is used for executing one condition from multiple conditions. It is
similar to an if-else-if ladder.
The switch statement consists of conditional-based cases and a default case.
Syntax of switch Statement in C
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}
How to use switch case Statement in C?
Before using the switch case in our program, we need to know about some rules of the switch
statement.
Rules of the switch case statement
Following are some of the rules that we need to follow while using the switch statement:
1. In a switch statement, the “case value” must be of “char” and “int” type.
2. There can be one or N number of cases.
3. The values in the case must be unique.
4. Each statement of the case can have a break statement. It is optional.
5. The default Statement is also optional.
// C program to Demonstrate returning of day based numeric
// value
#include <stdio.h>
int main()
{
// switch variable
int var = 1;
// switch statement
switch (var) {
case 1:
printf("Case 1 is Matched.");
break;
case 2:
printf("Case 2 is Matched.");
break;
case 3:
printf("Case 3 is Matched.");
break;
default:
printf("Default case is Matched.");
break;
}
return 0;
}
Output
Case 1 is Matched.
How switch Statement Work?
The working of the switch statement in C is as follows:
1. Step 1: The switch variable is evaluated.
2. Step 2: The evaluated value is matched against all the present cases.
3. Step 3A: If the matching case value is found, the associated code is executed.
4. Step 3B: If the matching code is not found, then the default case is executed if present.
5. Step 4A: If the break keyword is present in the case, then program control breaks out of the
switch statement.
6. Step 4B: If the break keyword is not present, then all the cases after the matching case are
executed.
7. Step 5: Statements after the switch statement are executed.
We can also understand the working of the switch statement in C using the flowchart.
Flowchart of Switch Statement
Flowchart of switch statement in C
int main()
{
int var = 2;
Case 2 is executed.
Case 3 is executed.Case 4 is executed.
Default in switch case
The default keyword is used to specify the set of statements to execute if there is no case
match.
It is optional to use the default keyword in a switch case. Even if the switch case statement does
not have a default statement, it would run without any problem.
Important Points About Switch Case Statements
1. Switch expression should result in a constant value
If the expression provided in the switch statement does not result in a constant value, it would
not be valid. Some valid expressions for switch case will be,
// Constant expressions allowed
switch(1+2+23)
switch(1*2+3%4)
// Driver Code
int main()
{
int day = 2;
// driver code
int main()
{
// switch variable
char choice;
// operands
int x, y;
while (1) {
printf("Enter the Operator (+,-,*,/)\nEnter x to "
"exit\n");
scanf(" %c", &choice);
// for exit
if (choice == 'x') {
exit(0);
}
case '-':
printf("%d - %d = %d\n", x, y, x - y);
break;
case '*':
printf("%d * %d = %d\n", x, y, x * y);
break;
case '/':
printf("%d / %d = %d\n", x, y, x / y);
break;
default:
printf("Invalid Operator Input\n");
}
}
return 0;
}
Output
Enter the operator (+, -, *, /)
Enter x to exit
+
Enter the two numbers: 100 + 200
100 + 200 = 300
Advantages of C switch Statement
1. Easier to read than if else if.
2. Easier to debug and maintain for a large number of conditions.
3. Faster execution speed.
Disadvantages of C switch Statement
1. Switch case can only evaluate int or char type.
2. No support for logical expressions.
3. Have to keep in mind to add a break in every case.
Conclusion
In this article, we discussed the switch statement in C programming and how to use it. It is a
conditional statement like the if-else-if ladder having its own merits and demerits. It is mostly
preferred when the number of conditions to evaluate is large.
FAQs on C switch Statement
1. What is the switch case in C?
The switch case statement is a flow control statement in which we can define a switch variable
and then execute different code based on the value of the switch variable. It is an alternative of if
else if ladder.
2. What is the case in the switch statement in C?
The case keyword is used to define the different cases and their associated code in the switch
statement.
3. What does the break in the switch case do?
The break keyword is used to exit the switch block after executing the matching case.
4. What are the differences between switch and if else if ladder in C?
Following are the main differences between C switch and C if else if ladder:
switch if else if
Faster and easier to read for the large It can get messy when there are lots of
number of conditions. conditions.