UNIT -2 -Notes
Arithmetic Expressions and Precedence
Definition of Operators in C:
Operators in C are special symbols or keywords used to perform operations on variables and
values. These operations may include arithmetic, comparison, logical decision-making, value
assignment, and more.
They are the building blocks of any expression in C, allowing programmers to manipulate data and
control the program's behaviour.
Example:
int a = 10, b = 5;
int sum = a + b; // '+' is an arithmetic operator
Here, + is the operator, and a and b are the operands. The operator performs addition.
Types :
Arithmetic operators are used to perform mathematical operations in C. The common arithmetic
operators are
Operator Precedence: Operators have a predefined precedence level that determines the order of
evaluation in an expression. Multiplication, division, and modulus have higher precedence than addition
and subtraction. Parentheses can be used to change the order of evaluation.
Turbo C++ Example (Arithmetic Operators):
#include <stdio.h>
#include <conio.h>
int main()
{
int a = 10, b = 5;
printf("Addition: %d\n", a + b);
printf("Subtraction: %d\n", a - b);
printf("Multiplication: %d\n", a * b);
printf("Division: %d\n", a / b);
printf("Modulus: %d\n", a % b);
getch();
return 0;
}
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
2. Relational Operators
Relational operators compare two values and return a Boolean result (1 for true, 0 for false). They
include:
Turbo C++ Example (Relational Operators):
#include <stdio.h>
#include <conio.h>
int main ()
{
int x = 10, y = 20;
printf ("x == y: %d\n", x == y);
printf ("x!= y: %d\n", x != y);
printf ("x > y: %d\n", x > y);
printf ("x < y: %d\n", x < y);
printf ("x >= y: %d\n", x >= y);
printf ("x <= y: %d\n", x <= y);
getch();
return 0;
}
Output:
x == y: 0
x != y: 1
x > y: 0
x < y: 1
x >= y: 0
x <= y: 1
Mixed Operands and Type Conversion
When different types of operands (e.g., int and float) are
used in the same expression, type conversion occurs. This
can be implicit (automatic) or explicit (manual casting or type
casting).
Type Casting in C is the process of converting one data
type into another.
It is mainly used to make calculations happen correctly
between different types, like between integers and floats.
There are two types of Type Casting in C:
1. Implicit Type Casting (Automatic Conversion)
o Done by the compiler automatically.
o Converts smaller data type to bigger data type safely.
2. Explicit Type Casting (Manual Conversion)
o Done by the programmer.
o We force the compiler to change the data type.
o Syntax: (new_data_type) variable
1. Implicit Type Casting Example (Automatic Conversion)
#include <stdio.h>
int main()
{
int a = 5;
float b = 2.5;
float result;
result = a + b;//int 'a' is automatically converted to
float
printf("Result = %f\n", result);
return 0;
}
Output:
Result = 7.500000
Here, a is automatically converted to float to match b.
Explicit Type Casting Example (Manual Conversion)
#include <stdio.h>
int main()
{
int x = 10, y = 4;
float result;
result = (float)x / y; // Forcefully convert x
into float
printf("Result = %.2f\n", result);
return 0;
}
Result = 2.50
Without explicit type casting, 10/4 would give 2 (integer division).
With (float)x, the division happens in floating-point, giving 2.50.
Why Type Casting is Important
To avoid wrong calculations (like integer division by mistake).
To control how operations happen between mixed data types.
To save or convert memory size depending on requirements.
Turbo C++ Example (Implicit and Explicit Type Conversion):
#include <stdio.h>
#include <conio.h>
int main()
{
int a = 5;
float b = 2.5, result;
// Implicit type conversion
result = a + b;
printf("Implicit Conversion: %f\n", result);
// Explicit type conversion
result = (float) a / 2;
printf("Explicit Conversion: %f\n", result);
getch();
return 0;
}
Output:
Implicit Conversion: 7.500000
Explicit Conversion: 2.500000
4. Logical Operators
Logical operators are used to perform logical operations and return
either true (1) or false (0).
Logical AND (&&): Returns true if both operands are true.
Logical OR (||): Returns true if at least one operand is true.
Logical NOT (!): Reverses the logical state of the operand.
Turbo C++ Example (Logical Operators):
3. Logical Operators
#include <stdio.h>
int main()
{
int a = 10, b = 20;
printf("(a < b) && (b < 30): %d\n", (a < b) && (b < 30));
printf("(a > b) || (b == 20): %d\n", (a > b) || (b == 20));
printf("!(a == b): %d\n", !(a == b));
return 0;
}
Output:
(a < b) && (b < 30): 1
(a > b) || (b == 20): 1
!(a == b): 1
5. Bitwise Operations
Bitwise operators perform operations on individual bits of integers.
AND (&): 1 if both bits are 1.
OR (|): 1 if one of two bits is 1.
XOR (^): 1 if only one of the two bits is 1.
Turbo C++ Example (Bitwise Operators):
#include <stdio.h>
#include <conio.h>
int main()
{
int x = 5, y = 3;
printf("x & y = %d\n", x & y); // Bitwise AND
printf("x | y = %d\n", x | y); // Bitwise OR
printf("x ^ y = %d\n", x ^ y); // Bitwise XOR
getch();
return 0;
}
Output:
x&y=1
x|y=7
x^y=6
6. Assignment Operator
Assignment operators are used to assign values to variables.
The basic assignment operator is =.
Compound assignment operators include +=, -=, *=, /=, and %=.
#include <stdio.h>
#include <conio.h>
int main()
{
int x = 10;
x += 5; // x = x + 5
printf ("x after += 5: %d\n", x);
x *= 2; // x = x * 2
printf("x after *= 2: %d\n", x);
getch();
return 0;
}
Output:
x after += 5: 15
x after *= 2: 30
7. Operator Precedence and Associativity
Precedence: Determines the order in which operators are
evaluated.
Associativity: Determines the direction of evaluation when
operators have the same precedence (left to right or right to left).
#include <stdio.h>
#include <conio.h>
int main()
{
int a = 10, b = 5, c = 2;
int result = a + b * c; // Multiplication happens before
addition
printf("Result: %d\n", result); // Output: 20
getch();
return 0;
}
Output:
Result: 20
Operator precedence means the order in which operators are evaluated in an expression when there
are multiple operators.
Operators with higher precedence are evaluated before operators with lower precedence.
If two operators have the same precedence, their associativity (left-to-right or right-to-left) decides the
order.
Operator Precedence and Associativity Chart
Operator Precedence Associativity
() (Parentheses) Highest Left to Right
[] (Array subscript) Highest Left to Right
. (Dot), -> (Arrow) Highest Left to Right
++, -- (Post, Pre-Increment/Decrement) High Right to Left
*, /, % (Multiplication, Division, Modulo) Medium Left to Right
+, - (Addition, Subtraction) Medium Left to Right
<<, >> (Bitwise Shift) Medium Left to Right
<, <=, >, >= (Comparison operators) Medium Left to Right
==, != (Equality) Medium Left to Right
& (Bitwise AND) Low Left to Right
^ (Bitwise XOR) Low Left to Right
| (Bitwise OR) Low Left to right
&& (Logical AND) Low Left to Right
|| (Logical OR) Low Left to right
?: (Conditional or Ternary) Low Right to Left
= (Assignment) Low Right to Left
+=, -=, *=, /=, etc. (Compound Assignment) Low Right to Left
, (Comma) Lowest Left to Right
Key Points:
1. Highest Precedence: Operators like parentheses () and array subscripts [] are evaluated first.
2. Right-to-Left Associativity: Operators like ++, -- (increment/decrement), assignment (=), and
ternary operator (?:) are evaluated right to left.
3. Left-to-Right Associativity: Most operators, like arithmetic (+, -, *), comparison (<, >, ==), and
logical (&&, ||), are evaluated left to right.
Example:
int x = 2 + 3 * 5;
Here, * (multiplication) has higher precedence than + (addition).
So, 3 * 5 = 15 is evaluated first.
Then, 2 + 15 = 17.
Conditional Operator
?:
The conditional operator is also called the ternary operator
because it works with three operands.
It provides a shorthand way of writing simple if-else
conditions.
Syntax:
condition ? expression_if_true: expression_if_false;
If condition is true, expression_if_true is executed.
If condition is false, expression_if_false is executed.
Example 1: Find maximum of two numbers
int a = 10, b = 20;
int max = (a > b)? a : b;
printf("Maximum is %d", max);
Output: Maximum is 20
Example : Assigning pass/fail based on marks
int marks = 45;
char grade = (marks >= 50) ? 'P' : 'F';
printf("Grade: %c", grade);
Output: Grade: F
It's best to use conditional operator when the logic is
very simple.
If it's complicated, better to use normal if-else for
better readability.
1. Basic Ternary Operator Example
#include <stdio.h>
int main() {
int a = 10, b = 20;
int max = (a > b) ? a : b;
printf("Max value is: %d\n", max);
return 0;
}
Ternary Operator Syntax:
condition ? value_if_true : value_if_false;
Here, (a > b) is the condition.
o If true, a will be assigned to max.
o If false, b will be assigned to max.
Output:
Max value is: 20
2. Ternary Operator with Nested Condition
#include <stdio.h>
#include<stdio.h>
int main()
{
int a = 10, b = 20, c = 15;
int largest =(a > b)? ((a > c)?a:c): ((b>c)? b:c);
printf ("Largest value is: %d\n", largest);
return 0;
}
3. Ternary Operator for Even or Odd Check
#include <stdio.h>
int main() {
int num = 7;
printf("%d is %s\n", num, (num % 2 == 0) ? "Even" : "Odd");
return 0;
8. Conditional Branching
Conditional branching allows you to execute different parts of code based on certain conditions.
Conditional Statements in C
Conditional statements are used to make decisions in a
program based on certain conditions.
The common types in C are:
1. if Statement
Syntax:
if(condition)
{
// Code to execute if condition is
true
}
Example:
int x = 10;
if (x > 0)
{
printf ("x is positive\n");
}
2. if-else Statement
Syntax:
if(condition)
{
// Executes if condition is true
}
else
{
// Executes if condition is false
}
Example:
int n = 7;
if(n % 2 == 0)
{
printf("Even\n");
}
else
{
printf("Odd\n");
}
[Link] if Ladder
Used to check multiple conditions one after [Link]:
if(condition1)
{
// Block 1
}
else if(condition2)
{
// Block 2
}
else if(condition3)
{
// Block 3
}
else
{
// Default block
}
Example:
int marks = 82;
if(marks >= 90)
{
printf("Grade A\n");
}
else if(marks >= 75)
{
printf("Grade B\n");
}
else if(marks >= 60)
{
printf("Grade C\n");
}
else
{
printf("Grade D\n");
}
4 . Nested if Statement
An if inside another if. Used for checking conditions inside a condition.
Syntax:
if (condition1)
{
if (condition2)
{
// Code if both condition1 and condition2 are
true
}
}
OR
if (condition 1)
{
if (condition 2)
{
//statements 1
}
else
{
//statements 2
}
}
else
{
if (condition 3)
{
//statements 3
}
else
{
//statements 4
}
}
Example:
int a = 15;
if (a > 0)
{
if (a % 3 == 0)
{
printf("Positive and divisible by 3\n");
}
else
{
printf("Positive but not divisible by 3\n");
}
}
✅ Summary Table
Statement Type Use Case Executes When
if Single condition Condition is true
if-else Two-way decision Either condition is true or false
else-if Multiple conditions First true condition's block
Nested if Condition inside a condition Both conditions must be true
Example Programs
✅ 1. Even or Odd
int num;
scanf("%d", &num);
if (num % 2 == 0)
printf("Even");
else
printf("Odd");
✅ 2. Positive, Negative, or Zero
int num;
scanf("%d", &num);
if(num > 0)
printf("Positive");
else if(num < 0)
printf("Negative");
else
printf("Zero");
✅ 3. Check Leap Year
int year;
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
printf("Leap Year");
else
printf("Not a Leap Year");
✅ 4. Greatest of Two Numbers
int a, b;
scanf("%d %d", &a, &b);
if (a > b)
printf("%d is greater", a);
else
printf("%d is greater", b);
✅ 5. Greatest of Three Numbers
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
if (a >= b && a >= c)
printf("%d is greatest", a);
else if (b >= a && b >= c)
printf("%d is greatest", b);
else
printf("%d is greatest", c);
✅ 6. Check Eligibility to Vote (Age ≥ 18)
int age;
scanf("%d", &age);
if (age >= 18)
printf("Eligible to vote");
else
printf("Not eligible");
✅ 7. Find Grade Based on Marks
int marks;
scanf("%d", &marks);
if (marks >= 90)
printf("Grade A");
else if (marks >= 75)
printf("Grade B");
else if (marks >= 50)
printf("Grade C");
else
printf("Fail");
✅ 8. Check Divisibility by 5 and 11
int num;
scanf("%d", &num);
if (num % 5 == 0 && num % 11 == 0)
printf("Divisible by both 5 and 11");
else
printf("Not divisible");
✅ 9. Check if Character is Vowel or Consonant
char ch;
scanf(" %c", &ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
printf("Vowel");
else
printf("Consonant");
\
10. Simple Calculator (if-else based on operator)
float a, b;
char op;
scanf("%f %f %c", &a, &b, &op);
if(op == '+')
printf("Sum: %.2f", a + b);
else if (op == '-')
printf("Difference: %.2f", a - b);
else if (op == '*')
printf("Product: %.2f", a * b);
else if (op == '/')
printf("Quotient: %.2f", a / b);
else
printf("Invalid operator");
Switch Statement in C
Definition:
The switch statement is a control statement that allows us to choose
between multiple options based on the value of a variable or expression.
Syntax:
switch(expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
...
default:
// statements (optional)
}
The default case is optional and runs if no other case matches.
Basic Example:
#include <stdio.h>
int main()
{
int day = 3;
switch(day)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
return 0;
}
Output:
Wednesday
Example with char Type:
#include <stdio.h>
int main()
{
char grade = 'B';
switch(grade)
{
case 'A':
printf("Excellent!");
break;
case 'B':
printf("Very Good!");
break;
case 'C':
printf("Good");
break;
default:
printf("Invalid grade");
}
return 0;
}
Calculator Example Using switch:
#include <stdio.h>
int main()
{
int a = 10, b = 5;
char op = '+';
switch(op)
{
case '+':
printf("Sum = %d", a + b);
break;
case '-':
printf("Difference = %d", a - b);
break;
case '*':
printf("Product = %d", a * b);
break;
case '/':
if (b != 0)
printf("Quotient = %d", a / b);
else
printf("Cannot divide by zero");
break;
default:
printf("Invalid operator");
}
return 0;
}
Key Points:
1. The expression must be of integer, char, or enum type.
2. Each case must have a unique constant value.
3. The break statement exits the switch block.
Without break, execution continues to the next case (fall-through).
Common Errors to Avoid:
Using non-integer expressions in switch.
Missing break causing unintended fall-through.
Repeating case values.
Using ranges (e.g., case x > 5) — not allowed.
🔹 When to Use switch Over if-else:
Use switch when:
You are comparing a single variable to many constant values.
Improves readability and reduces code complexity compared to long if-else-if chains.
#include <stdio.h>
int main()
{
int a = 6, b = 9;
if (a < b)
if (a + b < 10)
printf("Low\n");
else if (a * b < 50)
printf("Medium\n");
else if (a * b > 100)
printf("High\n");
return 0;
}
#include <stdio.h>
int main()
{
int x = 4, y = 2;
if (x > 2)
if (y > 3)
printf("Alpha\n");
else if (x < 5)
printf("Beta\n");
else
printf("Gamma\n");
else
printf("Delta\n");
return 0;
}
#include <stdio.h>
int main()
{
int a = 3, b = 5, flag = 0;
if (a < b)
if (b - a == 2)
if (flag)
printf("YES\n");
else
printf("NO\n");
else
printf("MAYBE\n");
return 0;
}
#include <stdio.h>
int main() {
int x = 7;
if (x > 0)
if (x % 2 == 0)
if (x > 5)
printf("A\n");
else
printf("B\n");
else
if (x < 10)
printf("C\n");
else
printf("D\n");
return 0;
}
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("One ");
case 2: printf("Two ");
case 3: printf("Three ");
default: printf("Default");
}
return 0;
}
#include <stdio.h>
int main()
{
int a = 10;
switch (a % 3)
{
case 0: printf("Zero\n");
break;
case 1: printf("One\n");
break;
case 2: printf("Two\n");
break;
default: printf("Default\n");
}
return 0;
}
#include <stdio.h>
int main()
{
int x = 4;
switch (x)
{
case 1: printf("One ");
break;
default: printf("Default ");
case 4: printf("Four ");
break;
}
return 0;
}
#include <stdio.h>
int main()
{
int x = 10;
switch (x)
{
default: printf("Default ");
case 5: printf("Five ");
case 7: printf("Seven ");
case 10: printf("Ten ");
break;
case 12: printf("Twelve ");
break;
}
return 0;
}
#include <stdio.h>
int main()
{
int x = 1, y = 0;
if (x == 1)
if (y == 1)
printf("Both one\n");
else
printf("x is one\n");
return 0;
}
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
switch (ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
printf("It is a vowel.\n");
break;
default:
printf("It is not a vowel.\n");
}
return 0;
}