0% found this document useful (0 votes)
43 views112 pages

C Language Operators Explained

Modular program

Uploaded by

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

C Language Operators Explained

Modular program

Uploaded by

b0375070
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Operators used in C

• An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.
Operand- Operands are those on which the operator operates.
Expression- An expression is a sequence of operands and operators that reduces to a single value.
• C language has built-in operators & provides the following types of operators
1. Arithmetic Operators
2. Relational Operators
3. Equality operators
4. Logical Operators
5. Unary operators
6. Conditional operators
7. Bitwise Operators
8. Assignment Operators
9. Comma Operators
1. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc. on numerical values (constants and
variables).
1. Arithmetic Operators
#include <stdio.h> // Working of arithmetic operators
int main()
{
int a,b,sum,diff,product,quot,remainder;
printf(“Enter the values of a and b”);
scanf(“%d%d”,&a,&b);
sum=a+b;
diff=a-b;
product=a*b;
quot=a/b;
remainder=a%b;
printf(“Sum=%d\ndifference=%d\nproduct=%d\nquotient=%d\nremainder=%d\n”,sum,diff,product,qu
ot,remainder);
return 0;
}
• Write a C program to subtract 2 long integers.
#include<stdio.h>
void main()
{
long int a, b, diff=0;
printf(“Enter values of a and b\n”);
scanf(“%ld%ld”,&a,&b);
diff=a-b;
printf(“Difference = %ld”, diff);
}
2. Relational Operators
• Relational operators/Comparison operators in C are commonly used to check
the relationship between the two variables.

• Expressions that contain relational operators called relational expressions.

Operators Function
> Greater than Ex- 4>3 gives 1
< Less than Ex- 6<3 gives 0
>= Greater than equal to
<= Less than equal to
== Equal to
!= Not equal to
Write a C program to show the use of relational operators

return 0;
3. Equality operators
• C language supports 2 kinds of equality operators, == and !=
operators.
operators meaning
== returns 1 if both operands are equal, else 0
!= returns 1 if operands don’t have same value, else 0
4. Logical Operators
These operators are used to perform logical operations on the given
expressions. There are 3 logical operators in C.
Logical AND (&&)
• If both operands are non zero then the condition becomes true.
Otherwise, the result has a value of 0
Logical OR (||)
• The condition becomes true if any one of them is non-zero.
Otherwise, it returns false i.e., 0 as the value.
Logical NOT Operator ( ! )

• If the condition is true then the logical NOT operator will make it false
and vice-versa.
C program to demonstrate the use of Logical Operators

#include <stdio.h>// program to find largest of 3 numbers


void main()
{
int a = 10, b = 4, c = 9;
if (a > b && a>c)
printf("a is the greatest\n");
else if (b> a && b>c)
printf(“b is the greatest\n");
else
printf(“c is the greatest\n”);
}
5. Unary operators

• Unary operators act on single operands.


• 3 unary operators: unary minus, increment, decrement operators.

a. ) Unary Minus:
• When operand is preceded with minus sign the unary operator negates its value.
• If a number is positive, then it becomes negative when preceded with a unary minus
operator and if a number is negative, it becomes positive after applying unary minus
operator.
• Eg: int a, b=10;
a= - ( b );

Result: a =-10
b.) Increment and Decrement Operators

C programming has two operators

Increment (++)- increases the value of operand by 1


Decrement (--)- decreases the value of operand by 1.
These two operators are unary operators, meaning they only operate on a single
operand.
Increment Operators
• Increment Operators are the unary operators used to increment or add 1 to
the operand value.

• The Increment operand is denoted by the double plus symbol (++). It has
two types:

Pre Increment (prefix) and Post Increment(postfix) Operators.


Pre Increment operators
The pre-increment operator is used to increase the original value of the
operand by 1 before assigning it to the expression.

Ex- int x=10,y;

y=++x;

Is equivalent to

x=x+1;

y=x;
#include<stdio.h>
void main()
{
int a = 10, b;
b = ++a; Here first the value of a
printf("b = %d\n", b); increments and then is assigned
printf("a = %d\n", a);
to variable b. So both a and b
}
value will be 11.
Post Increment operators
The post-increment operator is used to increment the original value of
the operand by 1 after assigning it to the expression.

Ex- int x=10,y;

y=x++;

Is equivalent to

y=x;

x=x+1;
#include<stdio.h>
void main()
{
int a = 10, b;
b = a++;
printf("b = %d\n", b); Here first value of a(i.e., 10) is
printf("a = %d\n", a);
assigned to b and then value of a is
}
incremented. So b = 10 and a = 11 is
printed.
Pre decrement operators
The pre-decrement operator is used to decrease the original value of
the operand by 1 before assigning it to the expression.

Ex- int x=20,y;

y=--x;

Is equivalent to

x=x-1;

y=x;
Pre-decrement-
#include<stdio.h>
void main()
{
int a = 10, b;
b = --a;
printf("b = %d\n\n", b); Here first the value of a decrements
printf("a = %d\n", a);
and then is assigned to variable b.
}
So both a and b value will be 9.
Post decrement operators
The post-decrement operator is used to decrease the original value of
the operand by 1 after assigning it to the expression.

Ex- int x=20,y;

y=x--;

Is equivalent to

y=x;

x=x-1;
Decrement Operator
Post Decrement-
#include<stdio.h>
void main()
{
int a = 10, b;
b = a--; Here first value of a(i.e., 10) is
printf("b = %d\n\n", b); assigned to b and then value of a is
printf("a = %d\n", a);
decremented So b = 10 and a = 9 is
}
printed.
6. Bitwise Operators
• Bitwise operator works on bits and performs bit-by-bit operation.
• These operators include: bitwise AND, bitwise OR, bitwise XOR, Shift
operators.
• Bitwise AND(&): Bit in the first operand is ANDed with the corresponding bit
in second operand.
Ex:int a=10,b=6,c=0;
c=a&b;
10 0000 1010
06 0000 0110
0000 0010 c=2
• Bitwise XOR-
10101010^01010101=11111111
• Bitwise NOT-
~10101011=01010100

• Bitwise left shift-


x=00011101 x<<1 =00111010

• Bitwise right shift-


x=00011101 x>>1= 00001110
Homework
#include<stdio.h>
void main()
{
int a=27, b=39;
printf(“ a & b = %d” , a&b); // 3
printf(“ a | b = %d” , a|b); //63
printf(“ ~a = %d” , ~a); //-28
printf(“ ~b = %d” , ~b); //-40
printf(“ a ^ b = %d” , a^b); //60
printf(“ a << 1 = %d” , a<<1); //54
printf(“ b >>1 = %d” , b>>1); //19
}
7. Assignment Operator

• This operator is responsible to assign values to variables.


• Ex- int x=10;
• This assigns 10 to variable x.

Homework- Write a C program to demonstrate the use of assignment


operators.
8. Comma operator
• It takes two operands.
• It works by evaluating the first and discarding its value and then evaluates
the second and returns the value as the result of the expression.
• Comma separated operands when chained together are evaluated in left to
right sequence with right most value yielding the result of the expression.
• Among all the operators the comma operator has the lowest precedence.

Eg: int a=2, b=3,x=0;


x=(++a, b=b+a);
x=6
9. sizeof operator:
• It is a unary operator used to calculate the sizeof datatypes.
• Keyword used is “sizeof” .
• This operator is used to determine the amount of memory space that the
variable/expression/data type will take.

Ex: int a=10, result;


result =sizeof(a);
result=4
10.Conditional(ternary) operator
• Syntax-
exp1 ? exp2 : exp3
• Ex-
large = (a>b) ? a : b
Decision control and Looping statements

33
Conditional statements
• Conditional statements are used to execute a set of statements on some
conditions.

• If the given condition is true then the set of statements are executed
otherwise body is skipped and next statement will be executed..

34
Conditional statements
• There are different types of Conditional statements
• IF Condition
• IF ELSE Condition
• Nested IF ELSE condition
• Cascaded if-else or else if ladder
• Switch Case

35
Conditional statements
1. IF CONDITION

• It is a conditional statement, which is used to execute a set of statements on


some conditions.

• The condition must be of Boolean type expression.

• An expression, which returns only two value either TRUE or FALSE, is known
as Boolean type expression.

36
1. IF CONDITION

Syntax: if (condition)

statement 1;

statement n;

statement x;
If the condition evaluates to true, then statements of if block (
statement 1 to statement n) will be executed otherwise these
37
statements will be skipped and statement x will be executed.
Conditional statements
1. IF CONDITION
#include<stdio.h>
int main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
if(number==10)
printf("number is equals to 10");
return 0;
} 38
2. IF ELSE CONDITION

• It is known as double blocked conditional statements.

• It means, it has TRUE parts as well as FALSE part.

• If the given condition is true then the true part is executed otherwise false part
is executed.

39
2. IF ELSE CONDITION
Syntax: - if (CONDITION)
{
statement y;
}
else
{
statement x;
}
If the condition returns true, then the statements inside
the body of “if” are executed and the statements inside
body of “else” are skipped.
If the condition returns false then the statements inside
the body of “if” are skipped and the statements in “else”
are executed.
40
3. NESTED IF ELSE

• Using One If Statement Within Another If Statement Is Known As Nested If


else Statement.

• Nested if statements are often used when you must test a combination of
conditions before deciding on the proper action.

41
3. NESTED IF ELSE
if(conditional_expression1)
syntax- {
if(conditional_expression2)
{
statement1;
}
else
{
statement2;
}
}
else
{
statement 3;
} 42
4. Cascaded if-else or else if ladder

• With an if or if/else statement we evaluate a single true/false condition. A


cascaded if statement, on the other hand, makes it possible to evaluate several
conditions in a row.

43
4. Cascaded if-else or else if ladder
Syntax:

44
Dangling else problem
• This problem is created when there is no matching else for every if
statement.
• Ex-
if(a>b)
if(a>c)
printf(“a is greater than b & c”);
else
printf(“a is not greater than b & c”);
5. SWITCH CASE

• A switch case statement is a multi way decision statement that is a simplified version of an if-else block that
evaluates only one variable.

• It is generally used for menu- driven program, where we have to select one option out of several options at
a time.

• Rules –

• Each case label should be followed with a constant or a constant expression.

• Case labels must end with a colon.

• Control expression that follows the keyword switch must be of integral type(or any value that can be
converted to integer)

• Default label is executed only when the value of expression doesn’t match with any labeled constant
expression. 46
5. SWITCH CASE syntax
switch(variable)
Syntax:
{
case value1: statement;
break;
case value2: statement;
break;

default: statement;

47
Iterative statements
• Iterative statements are used to repeat the execution of a list of statements,
depending upon the value of an integer expression.

• The various looping constructs in C are:

(i) while Loop

(ii) do-while Loop

(iii) for Loop

48
Introduction to Conditional looping statements.
(i) while Loop

•The while loop evaluates the test Expression inside the parentheses ().

•If test Expression is true, statements inside the body of while loop are

executed. Then, test Expression is evaluated again.

•The process goes on until test Expression is evaluated to false.

•If test Expression is false, the loop terminates (ends).

49
(i) while Loop syntax

variable initialization;
while(condition)
{
Set of statements;
Increment/decrement statement;

50
(i) while Loop example-

#include<stdio.h> // Print numbers from 1 to 5


int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i=i+1;
}
return 0;
}
51
(i) while Loop
Step 1: initialized i to 1.

Step 2:When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is
executed. This prints 1 on the screen and the value of i is increased to 2.

Step 3:Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is
executed again. This prints 2 on the screen and the value of i is increased to 3.

Step4: This process goes on until i becomes 6. Then, the test expression i <= 5 will
52
be false and the loop terminates.
(ii) do- while Loop
• A do-while loop is similar to the while loop but the condition is always executed after the

body of a loop. It is also called an exit-controlled loop.

• The body is executed if and only if the condition is true. In some cases, we have to execute

a body of the loop at least once even if the condition is false.

• This type of operation can be achieved by using a do-while loop. In the do-while loop, the

body of a loop is always executed at least once.

53
(ii) do- while Loop

do
{
Statements;
} while (testExpression);

54
Introduction to Conditional looping statements.
(ii) do- while Loop

•The body of do...while loop is executed once. Only then,


the testExpression is evaluated.

•If testExpression is true, the body of the loop is executed


again and testExpression is evaluated once more.

•This process goes on until testExpression becomes false.

•If testExpression is false, the loop ends.


55
Difference between While and do- while Loop

56
Difference between While and do- while Loop

57
(iii) for loop
A for loop is a more efficient loop structure in 'C' programming which is used when
the loop has to be traversed for a fixed number of times. The for loop basically works
on three major aspects

(i) The initial value of the for loop is performed only once.

(ii) The condition is a Boolean expression that tests and compares the counter to a
fixed value after each iteration, stopping the for loop when false is returned.

(iii) The incrementation /decrementation increases (or decreases) the counter by a


set value. 58
(iii) for loop
Syntax: for (initial value; condition; incrementation or decrementation )
{
statements;
}

59
(iii) for loop
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < =10; i++)
{
printf("%d ", i);
}
return 0;
}

60
(iv) Nested for loop
• Nested loop means a loop statement inside another loop statement. That is
why nested loops are also called as “loop inside loop“.

• In nested for loop one or more statements can be included in the body of the
loop.

• In nested for loop, The number of iterations will be equal to the number of
iterations in the outer loop multiplies by the number of iterations in the inner
loop.
61
(iv) Nested for loop
• When the control moves from outer loop to inner loop the control remains
in the inner loop until the inner loop condition fails, once the condition fails
the control continues with the outer loop condition Again when the control
comes to inner loop the inner loop is reset to the initial value.

• The Nested for loop stops execution when the outer for loop condition fails

62
(iv) Nested for loop
Syntax:

63
(iv) Nested for loop

64
UnConditional looping statements.
• An unconditional statements are the statements which transfer the control or
flow of execution unconditionally to another block of statements. They are
also called jump statements.

• Following are the unconditional control transfer statements.

(i) break

(ii)continue

(iii) goto

65
UnConditional looping statements.
i) break Statement: A break statement terminates the execution of the loop and
the control is transferred to the statement immediately following the loop. i.e.,
the break statement is used to terminate loops or to exit from a switch.

Syntax :

break;

66
UnConditional looping statements.
i) break Statement:

#include<stdio.h>
void main()
{
int i=1;
while(i<=5)
{
if(i==3)
break;
printf(“%d\t”,i);
i++;

}
}
67
UnConditional looping statements.
(ii) continue statement:

• The continue statement tells the compiler “Skip the following Statements and
continue with the next Iteration”.

• It is a jump statement that is used to bring the program control to the


start of the loop.

Syntax :
continue;
68
UnConditional looping statements.
(ii) continue statement:
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=4;i++)
{
if(i==3)
continue;
printf("%d\t",i);
}
return 0;
}
69
UnConditional looping statements.
(iii)goto statement :

“goto” statement is used to transfer control to a specified label.

Syntax: Forward jump Backward jump


goto label; label: statements;
............ ............
. ............. ………….
label: statements; goto label;

If the label statement is below the goto statement then it is


called forward jump. if the label statement is above the goto
statement then it is called backward jump
70
Type Conversion:
• It is a process of converting one data type to another data type.
• Type conversion is done when an expression has variables of
different data types.
• There are two types:
Implicit Type conversion ,
Explicit Type Conversion (Type casting)
Type Conversion:
1.) Implicit Type Conversion: This type of conversion is done by the compiler, so it is

called as implicit type conversion.

• Without user intervention this process is carried out.

• To evaluate the expression, data type is promoted from lower level to higher level.

Hierarchy (lower to higher) can be given as char, short,int,long,float,double

• Whenever we are converting lower data type variable into higher data type variable

then compiler will do it implicitly.


• Example- Consider the below code in which integer data type is
promoted to float.
float x;
int y = 3;
x = y;
Now x = 3.0 , as integer value is automatically converted into its
equivalent floating point representation.
2.) Explicit Type Conversion/Type casting:

• This type of conversion is done by the user, instead of being done

automatically. Type casting is also called as forced conversion.


• It is done when value of higher data type is to be converted to value of lower
data type.
• This type of conversion is under programmer’s control and not under
compiler’s control.
Example- To typecast a floating point variable into integer variable,

float salary=10000.50;
int amount;
amount= (int) salary;

When floating point numbers are converted into integers, digits


after decimal are truncated. So data is lost when this type of
conversion is done.
Homework
• Write a C program to convert a floating point number into
corresponding integer.

• Write a C program to convert a integer number into corresponding


floating point number.
Iterative statements
• Iterative statements are used to repeat the execution of a list of statements,
depending upon the value of an integer expression.

• The various looping constructs in C are:

(i) while Loop

(ii) do-while Loop

(iii) for Loop

77
(i) while Loop
•The while loop evaluates the test Expression (condition) inside the

parentheses ().

•If test Expression is true, statements inside the body of while loop are

executed. Then, test Expression is evaluated again.

•The process goes on until test Expression is evaluated to false.

•If test Expression is false, the loop terminates (ends).


78
(i) while Loop syntax

variable initialization;
while(test_Expression)
{
Set of statements;
Increment/decrement statement;

79
(i) while Loop example-

#include<stdio.h> // Print numbers from 1 to 5


int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
i=i+1;
}
return 0;
}
80
while Loop explanation-
Step 1: initialized i to 1.

Step 2:When i = 1, the test expression i <= 5 is true. Hence, the body of the while loop is
executed. This prints 1 on the screen and the value of i is increased to 2.

Step 3:Now, i = 2, the test expression i <= 5 is again true. The body of the while loop is
executed again. This prints 2 on the screen and the value of i is increased to 3.

Step4: This process goes on until i becomes 6. Then, the test expression i <= 5 will
81
be false and the loop terminates.
(ii) do- while Loop
• A do-while loop is similar to the while loop but the condition is always executed after the

body of a loop. It is also called an exit-controlled loop.

• The body is executed if and only if the condition is true. In some cases, we have to execute

a body of the loop at least once even if the condition is false.

• This type of operation can be achieved by using a do-while loop. In the do-while loop, the

body of a loop is always executed at least once.

82
(ii) do- while Loop

do
{
Statements;
} while (testExpression);

83
do- while Loop explanation-
•The body of do...while loop is executed once. Only then,
the testExpression is evaluated.

•If testExpression is true, the body of the loop is executed


again and testExpression is evaluated once more.

•This process goes on until testExpression becomes false.

•If testExpression is false, the loop ends.


84
Difference between While and do- while Loop

85
Difference between While and do- while Loop

86
(iii) for loop
A for loop is a more efficient loop structure in 'C' programming which is used when
the loop has to be traversed for a fixed number of times. The for loop basically works
on three major aspects

(i) The initial value of the for loop is performed only once.

(ii) The condition is a Boolean expression that tests and compares the counter to a
fixed value after each iteration, stopping the for loop when false is returned.

(iii) The incrementation /decrementation increases (or decreases) the counter by a


set value. 87
(iii) for loop
Syntax: for (initialization expression; test expression; incrementation or decrementation )

{
statements;
}

88
(iii) for loop example-
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < =10; i++)
{
printf("%d ", i);
}
return 0;
}

89
(iv) Nested for loop
• Nested loop means a loop statement inside another loop statement. That is why
nested loops are also called as “loop inside loop“.

• In nested for loop one or more statements can be included in the body of the loop.

The Nested for loop stops execution when the outer for loop condition fails .

• In nested for loop, The number of iterations will be equal to the number of
iterations in the outer loop multiplies by the number of iterations in the inner loop.

90
(iv) Nested for loop
Syntax:

for (initialization expression; test expression; incrementation or decrementation )


{
for(initialization expression; test expression; incrementation or decrementation )
{
statements;

}
}

91
UnConditional looping statements.
• An unconditional statements are the statements which transfer the control or
flow of execution unconditionally to another block of statements. They are
also called jump statements.

• Following are the unconditional control transfer statements.

(i) break

(ii)continue

(iii) goto

92
UnConditional looping statements.
i) break Statement: A break statement terminates the execution of the loop and
the control is transferred to the statement immediately following the loop. i.e.,
the break statement is used to terminate loops or to exit from a switch.

Syntax :

break;

93
UnConditional looping statements.
i) break Statement:

#include<stdio.h>
void main()
{
int i=1;
while(i<=5)
{
if(i==3)
break;
printf(“%d\t”,i);
i++;

}
}
94
UnConditional looping statements.
(ii) continue statement:

• The continue statement tells the compiler “Skip the following Statements and
continue with the next Iteration”.

• It is a jump statement that is used to bring the program control to the


start of the loop.

Syntax :
continue;
95
UnConditional looping statements.
(ii) continue statement:
#include<stdio.h>
int main()
{
int i;
for(i=0;i<=4;i++)
{
if(i==3)
continue;
printf("%d\t",i);
}
return 0;
}
96
UnConditional looping statements.
(iii)goto statement :

“goto” statement is used to transfer control to a specified label.

Syntax: Forward jump Backward jump


goto label; label: statements;
............ ............
. ............. ………….
label: statements; goto label;

If the label statement is below the goto statement then it is


called forward jump. if the label statement is above the goto
statement then it is called backward jump
97
Type Conversion:
• It is a process of converting one data type to another data type.
• Type conversion is done when an expression has variables of
different data types.
• There are two types:
Implicit Type conversion ,
Explicit Type Conversion (Type casting)
Type Conversion:
1.) Implicit Type Conversion: This type of conversion is done by the compiler, so it is

called as implicit type conversion.

• Without user intervention this process is carried out.

• To evaluate the expression, data type is promoted from lower level to higher level.

Hierarchy (lower to higher) can be given as char, short,int,long,float,double

• Whenever we are converting lower data type variable into higher data type variable

then compiler will do it implicitly.


• Example- Consider the below code in which integer data type is
promoted to float.
float x;
int y = 3;
x = y;
Now x = 3.0 , as integer value is automatically converted into its
equivalent floating point representation.
2.) Explicit Type Conversion/Type casting:

• This type of conversion is done by the user, instead of being done

automatically. Type casting is also called as forced conversion.


• It is done when value of higher data type is to be converted to value of lower
data type.
• This type of conversion is under programmer’s control and not under
compiler’s control.
Example- To typecast a floating point variable into integer variable,

float salary=10000.50;
int amount;
amount= (int) salary;

When floating point numbers are converted into integers, digits


after decimal are truncated. So data is lost when this type of
conversion is done.
Homework
• Write a C program to convert a floating point number into corresponding integer.

#include<stdio.h>
void main()
{
float a;
int b;
printf(“Enter a floating point number\n”);
scanf(“%f”,&a);
b=(int)a;
printf(“Integer variant of %f is = %d”,a,b);
}
Homework
• Write a C program to convert a integer number into corresponding floating point
number.

#include<stdio.h>
void main()
{
float a;
int b;
printf(“Enter an integer number\n”);
scanf(“%d”,&b);
a=(float)b;
printf(“Floating point variant of %d is = %f”,b,a);
}
Evaluation of Expressions in C
Evaluation of Expressions in C
Evaluation of Expressions in C
Evaluation of Expressions in C a=5

++a Is Incrementtor so
Executed First

10 + 4 * 3 / 2
1+2*5+3
4-2+6*3
a+b*a/b-a%b -> a=10,b=2
Evaluation of Expressions in C
1. If a=8, b=15 and c=4 calculate the expression
2*((a%5)*(4+(b–3)/(c+2)))
2. Evaluate the expression
a += b *= c -=5 , Given a=3, b=5, c=8.
3. Evaluate the expression
100 / 20 <= 10 – 5 + 100 % 10 – 20 == 5 >= 1 != 20
Evaluation of Expressions in C
Evaluation of Expressions in C
Evaluation of Expressions in C

You might also like