Unit 3: Control Structures

Conditional Statements

  • if Statement: Executes a block of code if a condition is true.
    if (condition) {
        // Code to execute if the condition is true
    }
    
  • if-else Statement: Executes one block of code if the condition is true and another if it’s false.
    if (condition) {
        // Code to execute if the condition is true
    } else {
        // Code to execute if the condition is false
    }
    

Loops

  • for Loop: Repeats a block of code for a specified number of iterations.
    for (int i = 0; i < 5; i++) {
        // Code to repeat
    }
    
  • while Loop: Repeats a block of code as long as a condition is true.
    while (condition) {
        // Code to repeat
    }
    

Unit 4: Methods

Defining Methods

  • Method Signature: Consists of the method name and parameter list.
    returnType methodName(parameter1Type parameter1Name, parameter2Type parameter2Name) {
        // Method body
    }
    

Calling Methods

  • Method Call: Execute a method’s code by calling it with appropriate arguments.
    int result = methodName(arg1, arg2);
    

Method Overloading

  • Method Overloading: Defining multiple methods with the same name but different parameter lists.
    int sum(int a, int b) {
        return a + b;
    }
    
    double sum(double a, double b) {
        return a + b;
    }
    

Return Statements

  • Return Statement: Used to return a value from a method with a return type.
    int add(int a, int b) {
        return a + b;
    }
    

Recursion

  • Recursion: A method calls itself to solve a problem.
    int factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }