Skip to main content
Control Statements
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/
  6. Java Programming Slidev Presentations/

Control Statements

·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

Control Statements
#

Lecture 8
#

Java Programming (4343203)
Diploma in ICT - Semester IV
Gujarat Technological University

Press Space for next page

layout: default
#

Learning Objectives
#

By the end of this lecture, you will be able to:

  • ๐ŸŽฏ Master decision statements (if, if-else, switch)
  • ๐Ÿ”„ Implement loop statements (while, do-while, for)
  • ๐Ÿš€ Use jump statements (break, continue, return)
  • ๐Ÿ—๏ธ Build complex control flow structures
  • ๐Ÿงฎ Solve practical problems using control statements
  • ๐Ÿ“ Practice with syllabus-required exercises

Let's control the flow of our programs! ๐Ÿ”„๐ŸŽฏ

layout: center
#

Control Statements Overview
#

graph TD
    A[Control Statements] --> B[Decision Statements]
    A --> C[Loop Statements]
    A --> D[Jump Statements]
    
    B --> E[if statement]
    B --> F[if-else statement]
    B --> G[switch statement]
    
    C --> H[while loop]
    C --> I[do-while loop]
    C --> J[for loop]
    
    D --> K[break]
    D --> L[continue]
    D --> M[return]
    
    style B fill:#e3f2fd
    style C fill:#e8f5e8
    style D fill:#fff3e0
    style E fill:#f3e5f5
    style F fill:#f3e5f5
    style G fill:#f3e5f5
Control Flow: The order in which program statements are executed

layout: default
#

If Statement
#

๐ŸŽฏ Simple If Statement
#

// Syntax
if (condition) {
    // statements to execute if condition is true
}

// Example 1: Basic if
int age = 20;
if (age >= 18) {
    System.out.println("You can vote!");
}

// Example 2: Multiple conditions
int marks = 85;
if (marks >= 40) {
    System.out.println("You passed!");
}
if (marks >= 75) {
    System.out.println("You got distinction!");
}

// Example 3: Without braces (single statement)
int score = 95;
if (score == 100)
    System.out.println("Perfect score!");

โš ๏ธ Important Points
#

  • Condition must be boolean expression
  • Braces optional for single statement
  • Use braces for better readability
  • Multiple if statements are independent

๐Ÿ” Real-World Example
#

// Student eligibility checker
public class StudentEligibility {
    public static void main(String[] args) {
        int attendance = 80;
        int marks = 85;
        
        System.out.println("=== Eligibility Check ===");
        
        if (attendance >= 75) {
            System.out.println("โœ“ Attendance requirement met");
        }
        
        if (marks >= 40) {
            System.out.println("โœ“ Passing marks achieved");
        }
        
        if (marks >= 90) {
            System.out.println("๐Ÿ† Outstanding performance!");
        }
    }
}

layout: default
#

If-Else Statement
#

๐Ÿ”€ Basic If-Else
#

// Syntax
if (condition) {
    // statements if condition is true
} else {
    // statements if condition is false
}

// Example 1: Even/Odd checker
int number = 17;
if (number % 2 == 0) {
    System.out.println(number + " is even");
} else {
    System.out.println(number + " is odd");
}

// Example 2: Grade evaluator
int percentage = 78;
if (percentage >= 60) {
    System.out.println("First class");
} else {
    System.out.println("Second class");
}

๐Ÿ—๏ธ Nested If-Else
#

// Example: Complete grade system
int marks = 85;

if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 80) {
    System.out.println("Grade B");
} else if (marks >= 70) {
    System.out.println("Grade C");
} else if (marks >= 60) {
    System.out.println("Grade D");
} else {
    System.out.println("Grade F");
}

// Nested conditions
int age = 25;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("Can drive");
    } else {
        System.out.println("Need driving license");
    }
} else {
    System.out.println("Too young to drive");
}

layout: default
#

Switch Statement
#

๐ŸŽ›๏ธ Switch Syntax and Usage
#

// Syntax
switch (expression) {
    case value1:
        // statements
        break;
    case value2:
        // statements
        break;
    default:
        // default statements
        break;
}

// Example 1: Day of the week
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    default:
        System.out.println("Weekend");
        break;
}

๐Ÿ“ Practical Examples
#

// Calculator using switch
char operator = '+';
double num1 = 10.5, num2 = 3.2;
double result;

switch (operator) {
    case '+':
        result = num1 + num2;
        System.out.println("Sum: " + result);
        break;
    case '-':
        result = num1 - num2;
        System.out.println("Difference: " + result);
        break;
    case '*':
        result = num1 * num2;
        System.out.println("Product: " + result);
        break;
    case '/':
        if (num2 != 0) {
            result = num1 / num2;
            System.out.println("Quotient: " + result);
        } else {
            System.out.println("Cannot divide by zero");
        }
        break;
    default:
        System.out.println("Invalid operator");
        break;
}

layout: default
#

Switch vs If-Else Comparison
#

๐Ÿ†š When to Use Switch
#

Use Switch When:

  • Multiple discrete values to check
  • Better readability for many conditions
  • Performance matters (slight advantage)
  • Working with int, char, String, enum

Switch Limitations:

  • Cannot use ranges (< > <= >=)
  • Cannot use complex conditions
  • Only equality comparison

๐Ÿ“Š Comparison Example
#

Using If-Else:

if (grade == 'A') {
    System.out.println("Excellent");
} else if (grade == 'B') {
    System.out.println("Good");
} else if (grade == 'C') {
    System.out.println("Average");
} else {
    System.out.println("Below average");
}

Using Switch:

switch (grade) {
    case 'A':
        System.out.println("Excellent");
        break;
    case 'B':
        System.out.println("Good");
        break;
    case 'C':
        System.out.println("Average");
        break;
    default:
        System.out.println("Below average");
        break;
}

layout: default
#

While Loop
#

๐Ÿ”„ While Loop Syntax
#

// Syntax
while (condition) {
    // statements to repeat
    // update condition variable
}

// Example 1: Count from 1 to 5
int count = 1;
while (count <= 5) {
    System.out.println("Count: " + count);
    count++;  // Important: update the counter
}

// Example 2: Sum of first n numbers
int n = 10;
int i = 1;
int sum = 0;
while (i <= n) {
    sum += i;
    i++;
}
System.out.println("Sum of first " + n + " numbers: " + sum);

๐Ÿ“ Reverse Digits Program
#

// Syllabus requirement: Reverse digits using while loop
import java.util.Scanner;

public class ReverseDigits {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        int original = number;
        int reversed = 0;
        
        while (number > 0) {
            int digit = number % 10;     // Get last digit
            reversed = reversed * 10 + digit; // Build reversed number
            number = number / 10;        // Remove last digit
        }
        
        System.out.println("Original number: " + original);
        System.out.println("Reversed number: " + reversed);
        
        sc.close();
    }
}
๐Ÿ’ก Key Concept: Extract digits using modulus (%) and division (/)

layout: default
#

Do-While Loop
#

๐Ÿ”„ Do-While Syntax
#

// Syntax
do {
    // statements to execute
    // update condition variable
} while (condition);

// Example 1: Menu-driven program
Scanner sc = new Scanner(System.in);
int choice;

do {
    System.out.println("\n=== Menu ===");
    System.out.println("1. Add");
    System.out.println("2. Subtract");
    System.out.println("3. Exit");
    System.out.print("Enter choice: ");
    choice = sc.nextInt();
    
    switch (choice) {
        case 1:
            System.out.println("Addition selected");
            break;
        case 2:
            System.out.println("Subtraction selected");
            break;
        case 3:
            System.out.println("Goodbye!");
            break;
        default:
            System.out.println("Invalid choice");
    }
} while (choice != 3);

๐Ÿ†š While vs Do-While
#

While Loop:

  • Condition checked first
  • May not execute at all
  • Entry-controlled loop

Do-While Loop:

  • Condition checked last
  • Executes at least once
  • Exit-controlled loop

๐ŸŽฏ Practical Example
#

// Input validation with do-while
Scanner sc = new Scanner(System.in);
int age;

do {
    System.out.print("Enter age (1-120): ");
    age = sc.nextInt();
    if (age < 1 || age > 120) {
        System.out.println("Invalid age! Try again.");
    }
} while (age < 1 || age > 120);

System.out.println("Valid age entered: " + age);

layout: default
#

For Loop
#

๐Ÿ”ข For Loop Syntax
#

// Syntax
for (initialization; condition; update) {
    // statements to repeat
}

// Example 1: Count from 1 to 10
for (int i = 1; i <= 10; i++) {
    System.out.println("Number: " + i);
}

// Example 2: Multiplication table
int number = 7;
System.out.println("Multiplication table of " + number);
for (int i = 1; i <= 10; i++) {
    System.out.println(number + " x " + i + " = " + (number * i));
}

// Example 3: Array traversal
int[] marks = {85, 90, 78, 92, 88};
for (int i = 0; i < marks.length; i++) {
    System.out.println("Student " + (i+1) + ": " + marks[i]);
}

๐Ÿ”ข Prime Numbers Generation
#

// Syllabus requirement: Generate first n prime numbers
import java.util.Scanner;

public class PrimeNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter how many primes to generate: ");
        int n = sc.nextInt();
        
        System.out.println("First " + n + " prime numbers:");
        
        int count = 0;
        int number = 2;
        
        while (count < n) {
            boolean isPrime = true;
            
            // Check if number is prime
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            
            if (isPrime) {
                System.out.print(number + " ");
                count++;
            }
            number++;
        }
        
        sc.close();
    }
}

layout: default
#

Enhanced For Loop (For-Each)
#

๐ŸŽฏ For-Each Syntax
#

// Syntax for arrays
for (dataType variable : array) {
    // use variable
}

// Example 1: Array traversal
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
    System.out.println("Number: " + num);
}

// Example 2: String array
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println("Hello, " + name);
}

// Example 3: Calculate sum
int[] marks = {85, 90, 78, 92, 88};
int total = 0;
for (int mark : marks) {
    total += mark;
}
double average = total / (double) marks.length;
System.out.println("Average marks: " + average);

๐Ÿ†š Traditional vs Enhanced For
#

Traditional For Loop:

  • Index access available
  • Can modify array elements
  • More control over iteration

Enhanced For Loop:

  • Cleaner syntax
  • Read-only access
  • Less error-prone
  • Better for simple traversal

๐Ÿ“ When to Use Each
#

// Use traditional for when you need index
for (int i = 0; i < arr.length; i++) {
    System.out.println("Index " + i + ": " + arr[i]);
    arr[i] *= 2;  // Modify elements
}

// Use enhanced for for simple reading
for (int value : arr) {
    System.out.println("Value: " + value);
    // Cannot modify array through 'value'
}

layout: default
#

Jump Statements
#

๐Ÿš€ Break Statement
#

// Break in loops
for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // Exit loop when i is 5
    }
    System.out.println(i);
}
// Output: 1 2 3 4

// Break in switch
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;  // Exit switch
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;  // Without this, execution continues
    default:
        System.out.println("Other day");
}

// Break in nested loops
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        if (i == 2 && j == 2) {
            break;  // Breaks inner loop only
        }
        System.out.println("i=" + i + ", j=" + j);
    }
}

โญ๏ธ Continue Statement
#

// Continue in loops
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    System.out.println(i);
}
// Output: 1 3 5 7 9

// Practical example: Input validation
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
    System.out.print("Enter a positive number: ");
    int num = sc.nextInt();
    
    if (num <= 0) {
        System.out.println("Invalid! Skipping...");
        continue;  // Skip processing this number
    }
    
    // Process valid number
    System.out.println("Square: " + (num * num));
}

// Continue with while loop
int count = 0;
while (count < 10) {
    count++;
    if (count % 3 == 0) {
        continue;  // Skip multiples of 3
    }
    System.out.println(count);
}

layout: default
#

Return Statement
#

๐Ÿ”™ Return in Methods
#

// Return with value
public static int calculateSum(int a, int b) {
    int sum = a + b;
    return sum;  // Return the calculated value
}

// Early return for validation
public static double calculateSqrt(double number) {
    if (number < 0) {
        System.out.println("Cannot calculate sqrt of negative");
        return -1;  // Early return for invalid input
    }
    return Math.sqrt(number);
}

// Return in main method
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    
    System.out.print("Enter your age: ");
    int age = sc.nextInt();
    
    if (age < 0) {
        System.out.println("Invalid age");
        return;  // Exit main method early
    }
    
    System.out.println("Your age is: " + age);
}

๐ŸŽฏ Practical Return Examples
#

// Grade calculator with early returns
public static char calculateGrade(int marks) {
    if (marks < 0 || marks > 100) {
        return 'X';  // Invalid marks
    }
    
    if (marks >= 90) return 'A';
    if (marks >= 80) return 'B';
    if (marks >= 70) return 'C';
    if (marks >= 60) return 'D';
    return 'F';
}

// Search function with return
public static int findElement(int[] array, int target) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            return i;  // Return index when found
        }
    }
    return -1;  // Return -1 if not found
}

// Factorial with return
public static long factorial(int n) {
    if (n <= 1) {
        return 1;  // Base case
    }
    
    long result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

layout: default
#

Practical Exercises from Syllabus
#

๐ŸŽฏ Required Programming Tasks
#

๐Ÿ“ Exercise 1: Maximum of Three Numbers
#

import java.util.Scanner;

public class MaxOfThree {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter three numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        
        int max;
        
        // Using if-else statements
        if (a >= b && a >= c) {
            max = a;
        } else if (b >= a && b >= c) {
            max = b;
        } else {
            max = c;
        }
        
        System.out.println("Maximum: " + max);
        
        // Using conditional operator (ternary)
        int maximum = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
        System.out.println("Maximum (ternary): " + maximum);
        
        sc.close();
    }
}

๐Ÿ“ Exercise 2: Matrix Addition
#

import java.util.Scanner;

public class MatrixAddition {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] matrix1 = new int[3][3];
        int[][] matrix2 = new int[3][3];
        int[][] result = new int[3][3];
        
        // Input first matrix
        System.out.println("Enter first 3x3 matrix:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix1[i][j] = sc.nextInt();
            }
        }
        
        // Input second matrix
        System.out.println("Enter second 3x3 matrix:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                matrix2[i][j] = sc.nextInt();
            }
        }
        
        // Add matrices
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                result[i][j] = matrix1[i][j] + matrix2[i][j];
            }
        }
        
        // Display result
        System.out.println("Sum of matrices:");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(result[i][j] + " ");
            }
            System.out.println();
        }
        
        sc.close();
    }
}

layout: default
#

Nested Control Structures
#

๐Ÿ—๏ธ Complex Control Flow
#

// Pattern printing using nested loops
public class PatternPrinting {
    public static void main(String[] args) {
        
        // Pattern 1: Right triangle
        System.out.println("Right Triangle:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
        
        // Pattern 2: Number triangle
        System.out.println("\nNumber Triangle:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
        
        // Pattern 3: Pyramid
        System.out.println("\nPyramid:");
        for (int i = 1; i <= 5; i++) {
            // Print spaces
            for (int j = 1; j <= 5 - i; j++) {
                System.out.print(" ");
            }
            // Print stars
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

๐Ÿ” Number Analysis Program
#

import java.util.Scanner;

public class NumberAnalysis {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter a number: ");
        int number = sc.nextInt();
        int original = number;
        
        // Count digits
        int digitCount = 0;
        int temp = number;
        while (temp > 0) {
            digitCount++;
            temp /= 10;
        }
        
        // Check if Armstrong number
        temp = number;
        int sum = 0;
        while (temp > 0) {
            int digit = temp % 10;
            sum += Math.pow(digit, digitCount);
            temp /= 10;
        }
        
        // Display results
        System.out.println("Number: " + original);
        System.out.println("Digit count: " + digitCount);
        
        if (sum == original) {
            System.out.println("It's an Armstrong number!");
        } else {
            System.out.println("Not an Armstrong number.");
        }
        
        // Check if palindrome
        temp = number;
        int reversed = 0;
        while (temp > 0) {
            reversed = reversed * 10 + temp % 10;
            temp /= 10;
        }
        
        if (reversed == original) {
            System.out.println("It's a palindrome!");
        } else {
            System.out.println("Not a palindrome.");
        }
        
        sc.close();
    }
}

layout: default
#

Hands-On Assignment
#

๐Ÿ› ๏ธ Complete Programming Challenges
#

Task 1: Write a program to reverse digits of a number using while loop (syllabus requirement)
Task 2: Create a program to add two 3ร—3 matrices using nested for loops (syllabus requirement)
Task 3: Generate first n prime numbers using for and while loops (syllabus requirement)
Task 4: Build a menu-driven calculator using switch statement and do-while loop
Task 5: Create a number guessing game using all control statements

๐ŸŽฏ Success Criteria
#

  • Correct use of all control statement types
  • Proper input validation
  • Clean output formatting
  • Efficient algorithm implementation

layout: default
#

Best Practices and Common Mistakes
#

โœ… Best Practices
#

Code Structure:

  • Use proper indentation
  • Add meaningful comments
  • Use descriptive variable names
  • Keep loops simple and focused

Performance:

  • Avoid infinite loops
  • Use appropriate loop type
  • Minimize nested loop depth
  • Break/continue when needed

Readability:

  • Use braces even for single statements
  • Limit nesting levels
  • Group related conditions

โŒ Common Mistakes
#

Infinite Loops:

int i = 0;
while (i < 10) {
    System.out.println(i);
    // Forgot to increment i!
}

Missing Break in Switch:

switch (grade) {
    case 'A':
        System.out.println("Excellent");
        // Missing break!
    case 'B':
        System.out.println("Good");
        break;
}

Off-by-One Errors:

for (int i = 0; i <= array.length; i++) {
    // Should be i < array.length
}

layout: center class: text-center
#

Summary
#

๐Ÿ“– What We Learned

  • โ€ข Decision statements (if, if-else, switch)
  • โ€ข Loop statements (while, do-while, for)
  • โ€ข Jump statements (break, continue, return)
  • โ€ข Nested control structures
  • โ€ข Syllabus practical exercises
  • โ€ข Best practices and common pitfalls

๐ŸŽฏ Next Steps

  • โ€ข Introduction to Object-Oriented Programming
  • โ€ข POP vs OOP comparison
  • โ€ข Basic OOP concepts overview
  • โ€ข Real-world OOP examples
  • โ€ข Preparing for class and object concepts
Control flow mastered! Ready for OOP! ๐Ÿ”„๐ŸŽฏ

layout: center class: text-center
#

Questions & Discussion
#

โ“
Any questions about control statements, loops, or practical exercises?
Next lecture: **Introduction to Object-Oriented Programming**
Ready to enter the world of objects! ๐Ÿ‘