0% found this document useful (0 votes)
2 views

Module 2 5db59d0c5b79bc19ae607bc63fdbad04

The document provides an overview of various operators in the C programming language, including arithmetic, relational, equality, logical, unary, conditional, bitwise, and assignment operators. It explains their syntax, usage, and precedence, along with examples of C programs demonstrating their application. Additionally, it covers decision control statements like if, if-else, and switch-case for branching and looping in C.

Uploaded by

lsdslipp
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)
2 views

Module 2 5db59d0c5b79bc19ae607bc63fdbad04

The document provides an overview of various operators in the C programming language, including arithmetic, relational, equality, logical, unary, conditional, bitwise, and assignment operators. It explains their syntax, usage, and precedence, along with examples of C programs demonstrating their application. Additionally, it covers decision control statements like if, if-else, and switch-case for branching and looping in C.

Uploaded by

lsdslipp
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/ 116

Module 2

Operators in C
• An operator is a symbol that specifies the mathematical, logical, or relational
operation to be performed.
• C language supports different types of operators.
• Which can be used with variables and constants to form expressions.
• Arithmetic operators
• Relational operators
• Equality operators
• Logical operators
• Unary operators
• Conditional operators
• Bitwise operators
• Assignment operators
• Comma operators
• Size of operators
Arithmetic operators. ( a and b are operands)
Operation Operator Syntax Comment Remarks

Multiply * a*b Result = a*b

Divide / a/b Result = a/b Can be applied to any integer or floating


point numbers.
Addition + a+b Result = a+b
Subtraction - a-b Result = a-b
Modulus operators finds the remainder
of an integer division. (only applied to
Modulus % a%b Result = a%b integer operand)
Integer division
• When both operands of the division operator are integers, the division is
performed as an integer division.
• Integer division always results in an integer result.
• Result is always rounded-off by ignoring the remainder.
• To divide any number by zero – illegal operation – results in a run time division
by zero exception – thereby terminates the program.
Write a C-program to perform addition, subtraction,
division and multiplication on two integer numbers.
#include <stdio.h>
int main() {
int num1, num2;

// Input two integers


printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

// Perform operations
printf("Addition: %d + %d = %d\n", num1, num2, num1 + num2);
printf("Subtraction: %d - %d = %d\n", num1, num2, num1 - num2);
printf("Multiplication: %d * %d = %d\n", num1, num2, num1 * num2);

// Handle division to prevent division by zero


if (num2 != 0) {
printf("Division: %d / %d = %d\n", num1, num2, num1 / num2);
} else {
printf("Division by zero is not allowed.\n");
}

return 0;
}
• All arithmetic operators can accept a mix of integers and floating point numbers.
(except modulus operator).

• Precedence:
• Multiplication
• Division
• Modulus
• Addition
• subtraction
• Modulus operator finds the remainder of an integer division

• Modulus operator cab be applied only to integer operand


Relational operator
• Relational operator also known as comparison operator is an operator that
compares two values.
• Relational operators return true(1) or false(0) value, depending on the condition.

Operator Meaning
< Less than
> Greater than
<=
>= Less than or equal to
Greater than or equal to
• Characters are valid operands. Because if ‘A’ < ‘B’, where A is 65 and B is 66,
then the result would be 1 as 65 < 66.

• When arithmetic expression are used on either side of a relational operator,


then first the arithmetic expression will be evaluated and then the result will be
compared.

• Because arithmetic operators have highest priority over relational operators.


Equality operators

Opera Meaning
tors

== Returns 1 if both operands are equal, 0 otherwise

!= Returns 1 if operands do not have the same value, 0 otherwise


Write a program to show the use of relational and equality operators.
#include <stdio.h>

// Equality Operators
int main() { printf("\nEquality Operators:\n");
int a = 10, b = 20; printf("a == b : %d\n", a == b);
printf("a != b : %d\n", a != b);

printf("a = %d, b = %d\n\n", a, b); return 0; a = 10, b = 20


}

// Relational Operators Relational Operators:


a<b:1
printf("Relational Operators:\n");
a>b:0
printf("a < b : %d\n", a < b); a <= b : 1
printf("a > b : %d\n", a > b); a >= b : 0

printf("a <= b : %d\n", a <= b); Equality Operators:


printf("a >= b : %d\n", a >= b); a == b : 0
a != b : 1
Logical Operator
• C language supports three logical operators

• Logical AND (&&)


• Logical OR(||)
• Logical NOT(!)
Logical AND
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1
Logical OR
A B A||B
0 0 0
0 1 1
1 0 1
1 1 1
Logical NOT

A !A
0 1
1 0
Unary operator
• Unary minus (-)
• E.g.
• int a = 10;
• int b = -a; // b = -10.
Increment operator (++) and decrement operator(--)
• Increment operator – increases value of the operand by 1.
• Decrement operator – decreases value of the operand by 1.
• Two variants:
• Prefix (++x or -- x)
• Postfix(x++ or x -- ).
Increment prefix and postfix
• In prefix, The value of the operand will be altered before it is used.

• In postfix, The value operand will be altered after it is used.


Decrement ( prefix and postfix)
• In prefix, The value of the operand will be altered before it is used.

• In postfix, The value operand will be altered after it is used.


#include <stdio.h>
Post-increment:
a=5
int main() {
a++ = 5
int a = 5, b = 5; a after a++ = 6

// Post-increment: value is used first, then incremented


printf("Post-increment:\n");
printf("a = %d\n", a); // 5
printf("a++ = %d\n", a++); // 5 (then a becomes 6)
printf("a after a++ = %d\n\n", a); // 6
int x = 10, y = 10;

// Post-decrement
printf("Post-decrement:\n");
printf("x = %d\n", x); // 10
printf("x-- = %d\n", x--); // 10 (then x becomes 9)
printf("x after x-- = %d\n\n", x); // 9
// Pre-decrement
printf("Pre-decrement:\n");
printf("y = %d\n", y); // 10
printf("--y = %d\n", --y); // 9 (y becomes 9,
then used)
printf("y after --y = %d\n", y); // 9

return 0;
}
Write a c program to print the size of an char, long int, float, long,
short, double and long double Expected output is: size of char: 1 size
of int: 4 size of float: 4 size of long: 8 size of short: 2 size of double: 8
size of long double: 16
char ch = 'y';
printf("Size of ch: %zu\n", sizeof(ch)); // Will print 1
printf("Size of char: %zu\n", sizeof(char)); // Will also print 1
Use a char variable
char c = 'y';
printf("Size of variable c: %zu\n", sizeof(c));

Cast the character constant to char c


printf("Size of (char)'y': %zu\n", sizeof((char)'y’));

This forces the 'y' to be treated as a char instead of the default int

Use sizeof(char) directly


printf("Size of char type: %zu\n", sizeof(char));

This will always print 1 (by definition in C, a char is always 1 byte).


condition ? value_if_true : value_if_false
The ternary operator is a compact form of if-else:

b = 30 because (a == 1) is false.
•c = 20 because (a == 10) is true.
•This shows how the ternary operator can be used for concise
conditional assignments.
•Type casting changes the type temporarily for a specific operation.

•It doesn't affect the original variable (a is still int).

•The temporary conversion allows accurate float division instead of integer division.
1. Implicit Type Conversion (Type Promotion)
Done automatically by the compiler when different data types are mixed in an expression.
Type Conversion for Assignment in C
Widening Conversion
•Converting a smaller type to a larger type.
No data loss.

Here, a (1 byte) is assigned to b (typically 4 bytes). It’s a safe conversion.

Narrowing Conversion
•Converting a larger type to a smaller type.
•Possible data loss.

The fractional part 0.6 is truncated.


So, c gets the value 2.
•c.

A temporary 4-byte float memory is used to hold 11.0.


•This temporary float is used just for the calculation.
•The location is destroyed (freed) after the result is stored in C
Explicit Conversion to Prevent Integer Division
Hierarchy

char → short → int → long → float → double → long double

Moving forward = widening (safe).

Moving backward = narrowing (risky).


Conditional Operator
• The conditional operator or the ternary (? : ) is just like an if-else statement that can be
used within expressions.

• The syntax is exp1 ? exp2 : exp3

• exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result of the
expression.

• It is used in certain situations for replacing if-else condition phrases.

• Also known as ternary operator as It is neither a unary nor a binary operator, it takes
three operands.
e.g
large = (a>b) ? a : b;
the above code is to find the largest of two numbers.
first exp1, (a>b) is evaluated
if a is greater than b, then large = a, else large = b.
Nested conditional expression

int a = 5, b = 3, c=7, small;


small = ( a < b ? ( a <c ? a : c) : (b < c ? b : c ));
Bitwise operators
• Bitwise operators perform operation at bit level.
• These operators include: bitwise AND, bitwise OR, bitwise XOR and Shift
operators.

• Operands to be integer and treat them as sequence of bits. ( not applicable


for float or double variables).
Bitwise AND
• Bitwise AND (&) operator performs operation on bits. (it wont perform
operation on bytes, chars, integers etc.)
• When bitwise AND is used, the bit in the first operand is ANDed with the
corresponding bit in the second operand.
• Truth table is same as logical AND operation.

• If both bits are 1, the corresponding bit in the result is 1 and 0 otherwise.
• E. g
• 10101010 & 01010101
• Ans is : 00000000
Bitwise OR (|)
• The bit in the first operand is OR ed with the bit in the second operand.
• The truth table is same as OR operation.

• If one or both bits are 1, the corresponding bit in the result is 1 and 0
otherwise.
Bitwise XOR
• The bitwise XOR operator (^) performs operation on individual bits of the operands.

• The bit in the first operand is XORed with the bit in the second operand.
A B A^B

0 0 0

0 1 1

1 0 1

1 1 0
Bitwise NOT
• The bitwise NOT, or complement is a unary operator that performs logical
negation on each bit of the operand.
Shift operator

• C supports two bitwise shift operators.


• Shift left ( << )
• Shift right( >> )

• Shifts the bit either to the left or to the right

• Syntax : operand op num


multiple shifts of 1 to the left, results in multiplying the number by 2 over and
over again.

E.g
a << b .
where a is 5 and b is 2
binary of 5 is 101.
therefore it is 101 << 2
thus , a = 5*(2^2) = 20,
multiple shifts of 1 to the right, results in dividing the number by 2 over and over again.

E.g
a >> b .
where a is 5 and b is 2
binary of 5 is 101.
therefore it is 101 >> 2
thus , a = 5/(2^2) = 20,
Decision control and looping statement
Selection/Branching
Statement

Conditional Type Unconditional Type

If If-else If-else-if Switch


If statement
• It is the simplest form of decision control
statement. False
Test
expression

• Syntax of ‘if ’ statement True

Statement Block 1
If (test expression)
{
statement 1;
… Statement X
statement n;
}
Statement x;
#include<stdio.h>

int main()
{
int x = 10;
if(x>0) • Output is x= 11.
{
x++;
}
printf("x=%d", x);
return 0;
}
• Write a program to determine whether a person is eligible or not to vote.

#include<stdio.h>

int main()
{
int age;
printf("\n Enter the age:");
scanf("%d", &age);

if(age>=18)
{
printf("Eligible to vote\n");
}
return 0;
}
If-else statement
syntax of IF-ELSE statement Test
expression
if(test expression)
{ True False
statement block 1;
} Statement block 1 Statement block 2
else
{
statement block 2;
}
Statement x;
Statement x
• Write a c program to find whether the given number is even or odd.
#include<stdio.h>
int main()
{
int num;
printf("Enter any number:");
scanf("%d", &num);

if(num%2 == 0)
{
printf("%d is an even number", num);
}
else
{
printf("%d is an odd number", num);
}
return 0;
}
If – else – if statement → also Programmer can have as many else-if
branches
known as nested if construct
Test
True expression False
1
If(test expression 1)
{ Statement block1 Test
statement block 1;
expression
}
else if(test expression 2) 2
True False
{
statement block 2;
}
else Statement block 2 Statement block x
{
statement block x;
}
Statement y; Statement y
Write a program to test whether a number entered is positive, negative, or equal to
zero.
Switch case
• It is a multi way decision statements.
• Switch statements are mostly used in two situations
• when there is only one variable to evaluate in the expression.
• When many conditions are being tested for
True
Syntax of SWITCH statement
Value 1

Switch(variable) Statement Block 1


False
{
Case value1: True Value 2
statement block 1;
break;
Case value 2: Statement Block 2 False
statement block 2;
Value N
break; True
Default:
statement block D;
Statement Block N Statement Block D
False
break;
}
Statement x; Statement X
Generalized if – else statement
• Generalized switch statement
If(exp)
{
Switch() //do this
}
{
Else if(exp2)
Case 1: //do this {
Case 2: // do this //do this

Case 3: // do this }
Else if(exp 3)

{
Default: // do this //do this
} }
Write a program to enter a number from 1-7 and display the corresponding day of the week
using switch case statement.
Iterative statements
• Used to repeat the execution of a list of statements, depending on the value of an integer
expression.
• C language supports three types of iterative statements also known as looping statements.

• They are:
• While loop
• Do – while loop
• For loop
For loop
• It provides a mechanism to repeat a task until a particular condition is true.
• It is a definite loop because the programmer knows exactly how many times
the loop will repeat.
Syntax of FOR loop Initialize of loop variable

Condition False
for(initialization; condition; for loop
increment/decrement/update) variable

{ True

statement block; Statement block

}
Update the loop variable
Statement Y;

Statement Y
Write a program which prints first ‘n’ numbers using for loop.
Multiple initialization must be separated with a
comma operator
Nested loops
• Loops that can be placed inside another loops.

• A FOR loop can be used to control the number of times that a particular set
of statements will be executed.
• Another outer loop could be used to control the number of times that a
whole loop is repeated.
Write a program to print the following pattern using nested for loop.
Write a program to print the user input pattern using nested
for loop.
While loop (top checking loop)
• In the while loop, condition is
tested before any of the statements Statement x
in the statement block is executed.

Syntax
Update the condition
Condition
Statement x; expression
While(condition)
{ True
Statement block False
statement block;
}
Statement y
Statement y;
Write a program to calculate the sum of first 10 numbers
Do-while loop
• The do while loop is similar to the while loop.
• In do while loop, the condition is evaluated at the end of the loop.(bottom checking
loop)
• Test condition is enclosed in parentheses and followed by a semicolon.
• Even if the condition is false, the body of the loop is executed at least one
time.(major disadvantage)

• While loop and do – while loop is an indefinite loop as the loop can execute until
the user wants to stop.
syntax and flow chart of do – while loop
Statement x
Statement x;
do Statement block
{
statement block; Update the condition
expression
}
while(condition);
statement y; True
condition

False

Statement y
Break and continue statements
• Break statement is used to terminate the execution of the loop in which it
appears.
• It can be widely used in ‘for’, ‘while’, ‘do-while’ loops.
• Keyword: break;
Continue statement

• Is used in the body of the loop.

• When the compiler encounters a continue statement then the rest of the statements

in the loop are skipped and the control is unconditionally transferred to the loop-

continuation portion of the nearest enclosing loop. Syntax: continue;

You might also like