< All Topics
Print

BEU PPS Unit 2 notes – Operators, Conditional Branching, and Loops

Welcome back, future coders! Having built a strong foundation in problem-solving and basic program structure in Unit 1, we now move to Unit 2: Operators, Conditional Branching, and Loops. This unit is the heart of programming logic. It teaches your programs how to make decisions and repeat tasks efficiently—moving beyond simple sequential execution to dynamic and powerful behavior.

Mastering this unit is non-negotiable for becoming a proficient programmer. Every non-trivial program you write will use these concepts.


Understanding Operators & Expressions

What are Operators and Operands?

  • Operands: These are the data items (variables, constants) on which operations are performed. For example, in a + ba and b are operands.
  • Operators: These are symbols that tell the compiler to perform specific mathematical, relational, or logical operations. In a + b+ is the operator.

Types of Operators in C

C provides a rich set of operators to manipulate data. They are categorized based on their functionality.

1. Arithmetic Operators

These are used to perform basic mathematical operations.

OperatorNameExampleResult (if a=10, b=3)
+Additiona + b13
-Subtractiona - b7
*Multiplicationa * b30
/Divisiona / b3 (integer quotient)
%Modulus (Remainder)a % b1 (remainder of 10/3)

Important Note: Integer division truncates the decimal part. 10 / 3 is 3, not 3.333. To get a floating-point result, at least one operand must be a float (10.0 / 3).

2. Relational Operators

These are used to compare two values. The result of a relational operation is always an integer: 1 (True) or 0 (False).

OperatorNameExampleResult (if a=5, b=8)
==Equal toa == b0
!=Not equal toa != b1
>Greater thana > b0
<Less thana < b1
>=Greater than or equal toa >= b0
<=Less than or equal toa <= b1

3. Logical Operators

These are used to combine multiple conditions. They also return 1 (True) or 0 (False).

OperatorNameExampleDescription
&&Logical AND(a > 0) && (a < 10)True only if both conditions are true.
``Logical OR`(a == 5)(b == 5)`True if at least one condition is true.
!Logical NOT!(a == b)Reverses the logical state. True becomes false and vice versa.

Truth Tables:

Logical AND (&&)

ABA && B
000
010
100
111

Logical OR (||)

| A | B | A || B |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |

4. Bitwise Operators (Advanced)

These operators work on the individual bits of integer operands (int, char). They are used for low-level programming.

OperatorNameExampleDescription (a = 5 → 0101, b = 3 → 0011)
&Bitwise ANDa & b0101 & 0011 = 0001 (1)
``Bitwise OR`ab``01010011 = 0111` (7)
^Bitwise XORa ^ b0101 ^ 0011 = 0110 (6)
~Bitwise NOT (One’s Complement)~a~0101 = 1010 (in a 4-bit system, this is -6)
<<Left Shifta << 10101 << 1 = 1010 (10)
>>Right Shifta >> 10101 >> 1 = 0010 (2)

The Rulebook: Operator Precedence and Associativity

When multiple operators appear in a single expression, which one is evaluated first? This is determined by precedence (priority) and associativity (left-to-right or right-to-left order for operators of equal precedence).

Summary of Precedence (High to Low)

CategoryOperatorsAssociativity
Parentheses( )Left to Right
Unary+ + -- ! ~ + - (type cast)Right to Left
Multiplicative* / %Left to Right
Additive+ -Left to Right
Relational< <= > >=Left to Right
Equality== !=Left to Right
Logical AND&&Left to Right
Logical OR`Left to Right`
Assignment= += -= *= /=Right to Left

Example:
result = 5 + 2 * 3 > 4 && 10 / 2 == 5;
How is this evaluated?

  1. 2 * 3 = 6 (Multiplicative)
  2. 5 + 6 = 11 (Additive)
  3. 11 > 4 = 1 (True) (Relational)
  4. 10 / 2 = 5 (Multiplicative)
  5. 5 == 5 = 1 (True) (Equality)
  6. 1 && 1 = 1 (True) (Logical AND)
  7. result = 1 (Assignment)

Pro Tip: Use parentheses () to make complex expressions clear and force the order of evaluation you intend. It makes code easier to read and avoids errors.


Part 2: Controlling Program Flow – Conditional Branching

Conditional statements allow your program to make decisions and execute different code blocks based on whether a condition is true or false.

1. The if Statement

It is used to execute a block of code only if a condition is true.

Syntax:

if (condition) {
    // code to be executed if condition is true
}

Example:

int num = 10;
if (num > 0) {
    printf("The number is positive.\n");
}

2. The if-else Statement

It provides an alternative path of execution. If the condition is true, the if block runs; otherwise, the else block runs.

Syntax:

if (condition) {
    // code if condition is true
} else {
    // code if condition is false
}

Example:

int age = 16;
if (age >= 18) {
    printf("You are eligible to vote.\n");
} else {
    printf("You are not eligible to vote.\n");
}

3. The if-else if Ladder

It is used to check multiple conditions in sequence.

Syntax:

if (condition1) {
    // code if condition1 is true
} else if (condition2) {
    // code if condition2 is true
} else if (condition3) {
    // code if condition3 is true
} else {
    // code if all conditions are false
}

Example:

int marks = 85;
if (marks >= 90) {
    printf("Grade: A+\n");
} else if (marks >= 80) {
    printf("Grade: A\n");
} else if (marks >= 70) {
    printf("Grade: B\n");
} else {
    printf("Grade: C\n");
}
// Output: Grade: A

4. The Nested if Statement

An if or if-else statement inside another if or else block is called nesting.

Example:

int a = 10, b = 20, c = 5;
if (a > b) {
    if (a > c) {
        printf("A is largest.\n");
    } else {
        printf("C is largest.\n");
    }
} else {
    if (b > c) {
        printf("B is largest.\n");
    } else {
        printf("C is largest.\n");
    }
}
// Output: B is largest.

5. The switch-case Statement

It provides a clean alternative to a long if-else if ladder when you need to test a variable for equality against a list of constant values.

Syntax:

switch (expression) {
    case constant1:
        // code for constant1
        break;
    case constant2:
        // code for constant2
        break;
    ...
    default:
        // code if no case matches
}

Key Points:

  • The expression must be of integer or character type.
  • The break statement is crucial. It exits the switch block. Without it, execution will “fall through” to the next case.
  • The default case is optional and runs if no other cases match.

Example:

char grade = 'B';
switch (grade) {
    case 'A':
        printf("Excellent!\n");
        break;
    case 'B':
        printf("Well done!\n");
        break;
    case 'C':
        printf("Good.\n");
        break;
    default:
        printf("Invalid grade.\n");
}
// Output: Well done!

Repeating Tasks – Iteration and Loops

Loops are used to execute a block of code repeatedly as long as a specified condition is met. They are essential for automating repetitive tasks.

1. The for Loop

It is used when the number of iterations is known beforehand. It combines initialization, condition checking, and increment/decrement in one line.

Syntax:

for (initialization; condition; increment/decrement) {
    // code to be executed
}

Flowchart

For Loop Flow Chart in C

Example:

// Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
    printf("%d\n", i);
}

2. The while Loop

It is used when the number of iterations is not known, and you need to loop as long as a condition is true. The condition is checked before the execution of the loop body.

Syntax:

while (condition) {
    // code to be executed
}

Flowchart:

Flow chart of while loop in C

Example:

// Print numbers from 1 to 5
int count = 1;
while (count <= 5) {
    printf("%d\n", count);
    count++;
}

3. The do-while Loop

It is similar to the while loop, but it tests the condition after executing the loop body. This guarantees that the loop body is executed at least once.

Syntax:

do {
    // code to be executed
} while (condition);

Flowchart:

Flow Chart of Do While Loop in C

Example:

// Print numbers from 1 to 5
int num = 1;
do {
    printf("%d\n", num);
    num++;
} while (num <= 5);

Special Loop Control Statements

  • break;: Immediately exits the innermost loop or switch statement.
  • continue;: Skips the rest of the statements in the current iteration of the loop and jumps to the next iteration.

Example of break:

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break; // Exit loop when i is 5
    }
    printf("%d ", i);
}
// Output: 1 2 3 4

Example of continue:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue; // Skip the rest when i is 3
    }
    printf("%d ", i);
}
// Output: 1 2 4 5

Exam & Viva Prep – Unit 2

Quick Revision: Key Definitions

TermDefinition
OperatorA symbol that tells the compiler to perform a specific operation.
OperandThe data item on which an operator acts.
/ OperatorDivision. For integers, it returns the quotient.
% OperatorModulus. Returns the remainder of integer division.
Relational OperatorCompares two values. Returns 1 (True) or 0 (False). (e.g., ><==).
Logical OperatorCombines multiple conditions. (&&, `!`).
PrecedenceThe priority order in which operators are evaluated in an expression.
AssociativityThe order (L-to-R or R-to-L) to evaluate operators with the same precedence.
if statementExecutes a block of code only if a condition is true.
switch statementSelects one of many code blocks to execute based on a value.
for loopA loop used when the number of iterations is known.
while loopA loop that repeats as long as a condition is true (checks condition first).
do-while loopA loop that executes at least once and then repeats if a condition is true.
breakUsed to exit immediately from a loop or switch statement.
continueUsed to skip the current iteration of a loop and proceed to the next.

Practice MCQs

1. What is the result of 10 / 3 in C?
a) 3.333
b) 3
c) 4
d) 3.0

Answer b) 3 (Integer division truncates the decimal part)

2. Which operator has the highest precedence?
a) + (Addition)
b) = (Assignment)
c) && (Logical AND)
d) () (Parentheses)

Answer d) `()` (Parentheses)

3. What is the output of printf("%d", (5 > 3) && (2 == 2));?
a) 0
b) 1
c) 5
d) 2

b) 1 (Both conditions are true, so AND is true)

4. Which loop is guaranteed to execute at least once?
a) for loop
b) while loop
c) do-while loop
d) All of the above

Answer c) `do-while` loop

5. What does the break statement do?
a) Exits the current program.
b) Exits the current loop or switch statement.
c) Skips the current iteration.
d) Pauses the program.

Answer b) Exits the current loop or `switch` statement.

Important Theory & Viva Voce Questions

1. Differentiate between the / and % operators with examples.

Aspect/ (Division Operator)% (Modulus Operator)
PurposePerforms division and returns the quotient.Performs division and returns the remainder.
OperandsWorks with both integer and floating-point data types.Works only with integer data types.
Example 110 / 3 results in 3 (integer division).10 % 3 results in 1 (remainder).
Example 210.0 / 3.0 results in 3.333... (float division).10.0 % 3.0 results in a compile error.

2. Explain the concept of operator precedence and associativity. Why are parentheses important?

  • Operator Precedence: It defines the priority or order in which different operators in a complex expression are evaluated. Operators with higher precedence are evaluated before those with lower precedence. For example, multiplication * has higher precedence than addition +, so in 5 + 2 * 32 * 3 is evaluated first.
  • Associativity: It defines the order (left-to-right or right-to-left) in which operators of the same precedence level are evaluated. For example, the additive operators + and - have left-to-right associativity. So, in 10 - 5 + 2(10 - 5) is evaluated first, and then 5 + 2.
  • Importance of Parentheses ( ): Parentheses have the highest precedence. They are used to override the default precedence and associativity rules. They make the intended order of evaluation explicit, making the code clearer and less prone to logical errors.
    • Example: 5 + 2 * 3 evaluates to 11. But (5 + 2) * 3 forces the addition first, resulting in 21.

3. What is the difference between the while and do-while loops?

Aspectwhile Loopdo-while Loop
Condition CheckThe condition is checked at the beginning (pre-test loop).The condition is checked at the end (post-test loop).
Number of ExecutionsThe loop body may execute zero times if the condition is initially false.The loop body is guaranteed to execute at least once, even if the condition is false.
Syntaxwhile (condition) { ... }do { ... } while (condition);

4. When should you use a switch statement instead of an if-else if ladder?

switch statement is preferred over a long if-else-if ladder when:

  • The test expression is based on a single variable (or expression) that has an integer or character data type.
  • The branching decision is based on checking that variable for equality against a set of distinct constant values.

Use switch for:

switch(grade) { // Single variable, equality check
    case 'A': ... break;
    case 'B': ... break;
    ...
}

Use if-else-if for:

  • Testing ranges of values (e.g., if (marks >= 80)).
  • Evaluating conditions based on multiple variables (e.g., if (a > b && a > c)).
  • Checking conditions that are not just simple equality (e.g., if (number % 2 == 0)).

5. What is the purpose of the break statement in a switch-case block? What happens if it is omitted?

  • Purpose: The break statement is used to exit the entire switch block after the code for a matching case has been executed. It prevents the control from “falling through” to the subsequent case labels.
  • If Omitted: If a break statement is omitted, execution will continue (“fall through”) to the very next case block(s) until a break is encountered or the switch block ends. This is often a logic error, but it can be used intentionally for multiple cases that should execute the same code.

Example of Fall-Through:

switch (number) {
    case 1:
        printf("One ");
        // No break
    case 2:
        printf("and Two\n"); // This will also run if number is 1
        break;
}
// Input: 1 | Output: One and Two

6. Differentiate between the break and continue statements.

Aspectbreak Statementcontinue Statement
Action in LoopsTerminates the loop immediately. The control exits from the innermost loop.Skips the current iteration only. The control jumps to the next iteration of the same loop.
Action in switchUsed to terminate a case block.Not used inside a switch statement.
Examplefor(int i=1; i<=5; i++) { if(i==3) break; printf("%d", i); }
Output: 1 2
for(int i=1; i<=5; i++) { if(i==3) continue; printf("%d", i); }
Output: 1 2 4 5

7. Write a program to check if a number is prime.

#include <stdio.h>

int main() {
    int n, i, isPrime = 1; // Assume the number is prime initially

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // 0 and 1 are not prime numbers
    if (n == 0 || n == 1) {
        isPrime = 0;
    } else {
        for (i = 2; i <= n / 2; ++i) {
            // If n is divisible by any number between 2 and n/2, it's not prime
            if (n % i == 0) {
                isPrime = 0;
                break; // No need to check further
            }
        }
    }

    if (isPrime)
        printf("%d is a prime number.", n);
    else
        printf("%d is not a prime number.", n);

    return 0;
}

8. Write a program to find the factorial of a number using a for loop.

#include <stdio.h>

int main() {
    int n, i;
    unsigned long long factorial = 1; // Use long long for larger numbers

    printf("Enter a non-negative integer: ");
    scanf("%d", &n);

    // If user enters a negative number, show error
    if (n < 0) {
        printf("Error! Factorial of a negative number doesn't exist.");
    } else {
        for (i = 1; i <= n; ++i) {
            factorial *= i; // factorial = factorial * i;
        }
        printf("Factorial of %d = %llu", n, factorial);
    }

    return 0;
}

9. What will be the output of printf("%d", 5 + 2 * 3);? Explain why.

  • Output: 11
  • Explanation: This result is due to operator precedence. The multiplication operator * has a higher precedence than the addition operator +. Therefore, the expression 5 + 2 * 3 is evaluated as 5 + (2 * 3), which is 5 + 6, resulting in 11.

10. Explain the syntax and usage of the ternary operator (? :).

  • Syntax: condition ? expression_if_true : expression_if_false
  • Usage: The ternary operator is a shorthand conditional operator that is used to make simple decisions and assign values based on a condition. It is an alternative to a simple if-else statement.
    • First, the condition is evaluated.
    • If the condition is true (non-zero)expression_if_true is evaluated and becomes the result.
    • If the condition is false (zero)expression_if_false is evaluated and becomes the result.

Example 1: Assigning a value

int a = 5, b = 10;
int max = (a > b) ? a : b; // If a>b, max gets 'a', else gets 'b'
// Result: max = 10

Example 2: Printing a value

int number = 7;
printf("The number is %s", (number % 2 == 0) ? "Even" : "Odd");
// Output: The number is Odd
Table of Contents