Module 2 5db59d0c5b79bc19ae607bc63fdbad04
Module 2 5db59d0c5b79bc19ae607bc63fdbad04
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
// 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);
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
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.
Opera Meaning
tors
// 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);
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.
// 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));
This forces the 'y' to be treated as a char instead of the default int
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.
•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.
Narrowing Conversion
•Converting a larger type to a smaller type.
•Possible data loss.
• exp1 is evaluated first. If it is true, then exp2 is evaluated and becomes the result of the
expression.
• 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
• 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
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
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
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
}
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
• 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-