Recursive Functions Across 20 Languages

A comprehensive guide for CSE 240 and beyond

Python

Quick Reference

Variables

x = 10 name = "value" (dynamic typing)

Functions

def function_name(param): followed by indented body

Classes

class ClassName: with def __init__(self): for constructor

Comments

# single line or """multi-line"""

Control Flow

if condition: elif: else: for item in list: while condition:

Recursion Example: Study Hours Calculator

def calculate_study_hours(module_number):
    # Base case: Module 1 takes a baseline of 3 hours.
    if module_number == 1:
        return 3
    # Recursive step: Each subsequent module takes its number in hours,
    # plus all the hours from previous modules.
    else:
        return module_number + calculate_study_hours(module_number - 1)

# How many hours for the first 4 modules?
print(calculate_study_hours(4))  # Output: 10 (4 + 3 + 2 + 1)

JavaScript

Quick Reference

Variables

let x = 10; const y = 20; var z = 30; (use let/const)

Functions

function name(param) { } or const name = (param) => { }

Classes

class Name { constructor() { } method() { } }

Comments

// single line or /* multi-line */

Control Flow

if (condition) { } for (let i = 0; i < n; i++) { } while (condition) { }

Recursion Example: Concept Unlocker

function unlockConcept(currentConceptID, finalConceptID) {
  // Base case: You've reached the final concept for the week.
  if (currentConceptID >= finalConceptID) {
    console.log(`Concept ${finalConceptID} mastered! Module complete.`);
    return;
  }

  // Recursive step: Study the current concept and move to the next.
  console.log(`Studying concept ${currentConceptID}...`);
  unlockConcept(currentConceptID + 1, finalConceptID);
}

unlockConcept(1, 5);

C

Quick Reference

Variables

int x = 10; char c = 'a'; float f = 3.14; (static typing)

Functions

return_type function_name(type param) { }

Pointers

int *ptr = &x; *ptr (dereference) &var (address)

Structs

struct Name { type field; }; struct Name var;

Memory

malloc(size) free(ptr) sizeof(type)

Recursion Example: Pointer Tracer

#include <stdio.h>

// Imagine this function traces memory addresses.
void trace_pointer(int pointer_level) {
    // Base case: We've reached the actual data.
    if (pointer_level <= 0) {
        printf("Reached the value!\n");
        return;
    }

    // Recursive step: "Dereference" and go to the next level.
    printf("Level %d pointer -> \n", pointer_level);
    trace_pointer(pointer_level - 1);
}

int main() {
    trace_pointer(3); // Simulate a pointer-to-pointer-to-int (int***)
    return 0;
}

C++

Quick Reference

Variables

int x = 10; auto y = 5; (type inference)

Functions

return_type name(type param) { } references: void func(int &ref)

Classes

class Name { public: Name(); void method(); };

Namespaces

using namespace std; or std::cout

Templates

template<typename T> T func(T param) { }

Recursion Example: Project Compiler

#include <iostream>

void compile_project(int remaining_files) {
    // Base case: No files left to compile.
    if (remaining_files <= 0) {
        std::cout << "Project compiled successfully!" << std::endl;
        return;
    }

    // Recursive step: Compile one file and reduce the count.
    std::cout << "Compiling file " << remaining_files << "..." << std::endl;
    compile_project(remaining_files - 1);
}

int main() {
    compile_project(5);
    return 0;
}

Java

Quick Reference

Variables

int x = 10; String s = "text"; (static typing)

Functions

public static return_type name(type param) { }

Classes

public class Name { public Name() { } public void method() { } }

Access

public private protected default

Keywords

static final abstract extends implements

Recursion Example: Bug Debugger

public class Debugger {
    public static void debugCode(int bugsRemaining) {
        // Base case: No bugs left! Time to submit.
        if (bugsRemaining <= 0) {
            System.out.println("All bugs fixed. Code is clean!");
            return;
        }

        // Recursive step: Fix a bug and check the rest of the code.
        System.out.println("Squashing bug #" + bugsRemaining);
        debugCode(bugsRemaining - 1);
    }

    public static void main(String[] args) {
        debugCode(4);
    }
}

C#

Quick Reference

Variables

int x = 10; var y = "auto"; const int Z = 5;

Functions

public static return_type Name(type param) { }

Classes

public class Name { public Name() { } public void Method() { } }

Properties

public int Prop { get; set; }

LINQ

list.Where(x => x > 5).Select(x => x * 2)

Recursion Example: Topic Master

using System;

public class Student {
    public static void MasterTopic(int difficulty) {
        // Base case: The topic is easy enough to understand.
        if (difficulty <= 10) {
            Console.WriteLine("Topic mastered!");
            return;
        }

        // Recursive step: Study to reduce difficulty and try again.
        Console.WriteLine($"Topic difficulty is {difficulty}. Reviewing...");
        MasterTopic(difficulty - 15); // Each session helps!
    }

    public static void Main(string[] args) {
        MasterTopic(50); // Start with a tough topic.
    }
}

TypeScript

Quick Reference

Variables

let x: number = 10; const y: string = "text";

Functions

function name(param: type): returnType { }

Interfaces

interface Name { prop: type; method(): type; }

Types

type Name = string | number; type Obj = { x: number }

Generics

function name<T>(param: T): T { }

Recursion Example: Assignment Validator

function validateAssignment(checksLeft: number): void {
  // Base case: All checks passed.
  if (checksLeft <= 0) {
    console.log('Assignment is valid and ready to submit!');
    return;
  }

  // Recursive step: Perform a check and move to the next.
  console.log(`Running check #${checksLeft}... OK.`);
  validateAssignment(checksLeft - 1);
}

validateAssignment(3);

SQL

Quick Reference

Basic Queries

SELECT columns FROM table WHERE condition;

CRUD

INSERT INTO UPDATE table SET DELETE FROM

Joins

INNER JOIN LEFT JOIN RIGHT JOIN ON condition

Aggregates

COUNT() SUM() AVG() GROUP BY HAVING

CTEs

WITH name AS (SELECT ...) SELECT * FROM name;

Recursion Example: Course Prerequisites Path

-- Create a table of course prerequisites
CREATE TABLE Courses (id TEXT, prereq_id TEXT);
INSERT INTO Courses VALUES ('CSE100', NULL), ('CSE120', 'CSE100'), ('CSE240', 'CSE120');

-- Recursive Query to find the full path
WITH RECURSIVE course_path(id, path) AS (
  SELECT id, id FROM Courses WHERE id = 'CSE100' -- Base case
  UNION ALL
  SELECT c.id, p.path || ' -> ' || c.id -- Recursive step
  FROM Courses c, course_path p
  WHERE c.prereq_id = p.id
)
SELECT path FROM course_path WHERE id = 'CSE240';
-- Result: "CSE100 -> CSE120 -> CSE240"

Go

Quick Reference

Variables

var x int = 10 or x := 10 (short declaration)

Functions

func name(param type) returnType { }

Structs

type Name struct { field type }

Methods

func (receiver Type) methodName() { }

Goroutines

go functionCall() ch := make(chan type)

Recursion Example: Lab Task Completer

package main
import "fmt"

func completeLab(taskID int) {
    // Base case: Last task is done.
    if taskID <= 0 {
        fmt.Println("Lab project complete!")
        return
    }
    // Recursive step: Finish a task and start the next.
    fmt.Printf("Completing task #%d...\n", taskID)
    completeLab(taskID - 1)
}

func main() {
    completeLab(4)
}

Swift

Quick Reference

Variables

var x = 10 (mutable) let y = 20 (immutable)

Functions

func name(param: Type) -> ReturnType { }

Classes/Structs

class Name { init() { } func method() { } }

Optionals

var x: Int? if let x = optional { } x ?? default

Closures

{ (params) -> ReturnType in body }

Recursion Example: Exam Prep Countdown

func prepareForExam(daysLeft: Int) {
    // Base case: It's exam day!
    if daysLeft <= 0 {
        print("Good luck on the exam!")
        return
    }

    // Recursive step: Study for today and decrement the day count.
    print("\(daysLeft) days left. Time for a study session!")
    prepareForExam(daysLeft: daysLeft - 1)
}

prepareForExam(daysLeft: 3)

Kotlin

Quick Reference

Variables

var x = 10 (mutable) val y = 20 (immutable)

Functions

fun name(param: Type): ReturnType { }

Classes

class Name(val prop: Type) { fun method() { } }

Null Safety

var x: Int? x?.method() x ?: default x!!

Extensions

fun Type.newMethod() { }

Recursion Example: Problem Set Solver

fun solveProblemSet(problemsLeft: Int) {
    // Base case: No more problems to solve.
    if (problemsLeft <= 0) {
        println("Assignment finished!")
        return
    }

    // Recursive step: Solve one problem, then tackle the rest.
    println("Solving problem #$problemsLeft...")
    solveProblemSet(problemsLeft - 1)
}

fun main() {
    solveProblemSet(5)
}

R

Quick Reference

Variables

x <- 10 or x = 10 (assignment)

Functions

name <- function(param) { body }

Vectors

c(1, 2, 3) 1:10 seq(1, 10, 2)

Data Frames

df <- data.frame(col1 = c(...), col2 = c(...))

Conditionals

if (condition) { } else { } ifelse(test, yes, no)

Recursion Example: Dataset Analyzer

analyze_dataset <- function(data_points) {
  # Base case: The dataset is small enough for a final conclusion.
  if (data_points < 10) {
    return("Insight found!")
  }

  # Recursive step: Subset the data and analyze the smaller piece.
  cat("Analyzing", data_points, "points. Subsetting...\n")
  analyze_dataset(data_points / 2)
}

analyze_dataset(100)

PHP

Quick Reference

Variables

$x = 10; (all variables start with $)

Functions

function name($param) { return $value; }

Classes

class Name { public function __construct() { } }

Arrays

$arr = array(1, 2, 3); or $arr = [1, 2, 3];

Output

echo "text"; print "text"; var_dump($var);

Recursion Example: Study Guide Generator

<?php
function generate_study_guide($topics) {
    // Base case: No topics left in the array.
    if (empty($topics)) {
        return;
    }
    
    // Recursive step: Print the first topic and process the rest.
    $current_topic = array_shift($topics);
    echo "<li>$current_topic</li>";
    generate_study_guide($topics);
}

$module_topics = ['Pointers', 'Structs', 'File I/O'];
echo "<ul>";
generate_study_guide($module_topics);
echo "</ul>";
?>

Ruby

Quick Reference

Variables

x = 10 (local) @x (instance) @@x (class) $x (global)

Functions/Methods

def name(param) body end

Classes

class Name; def initialize; end; end

Blocks

{ |param| body } or do |param| body end

Arrays/Hashes

[1, 2, 3] {key: value} .each .map

Recursion Example: Flashcard Reviewer

def review_flashcards(cards)
  # Base case: No cards left to review.
  if cards.empty?
    puts "All cards reviewed!"
    return
  end

  # Recursive step: Review the top card, then the rest of the deck.
  current_card = cards.shift
  puts "Reviewing: #{current_card}"
  review_flashcards(cards)
end

flashcards = ["Paradigm", "Pointer", "Recursion"]
review_flashcards(flashcards)

Rust

Quick Reference

Variables

let x = 10; (immutable) let mut y = 20; (mutable)

Functions

fn name(param: type) -> ReturnType { }

Structs

struct Name { field: Type } impl Name { fn method(&self) { } }

Ownership

&x (borrow) &mut x (mutable borrow) move

Error Handling

Result<T, E> Option<T> match ? operator

Recursion Example: Memory Safety Checker

fn check_memory_safety(block_id: u32) {
    // Base case: Innermost block is reached and is safe.
    if block_id == 0 {
        println!("All blocks are memory safe.");
        return;
    }

    // Recursive step: Verify current block and check its parent.
    println!("Checking block {} for safety... OK.", block_id);
    check_memory_safety(block_id - 1);
}

fn main() {
    check_memory_safety(3);
}

Dart

Quick Reference

Variables

var x = 10; int y = 20; final z = 30; const W = 40;

Functions

ReturnType name(Type param) { } or name(param) => expression;

Classes

class Name { Name(); void method() { } }

Null Safety

int? x; x! (assert non-null) x ?? default

Async

Future<T> async { } await

Recursion Example: UI Widget Builder

void buildUiWidget(int complexity) {
  // Base case: The simplest widget needs no more nesting.
  if (complexity <= 1) {
    print('  Building final Text Widget...');
    return;
  }

  // Recursive step: Build a container and nest a simpler widget inside.
  print('Building Container Widget of complexity $complexity...');
  buildUiWidget(complexity - 1);
}

void main() {
  buildUiWidget(3);
}

MATLAB

Quick Reference

Variables

x = 10; A = [1 2; 3 4]; (matrices)

Functions

function output = name(input) body end

Indexing

A(1,2) (1-indexed) A(:,1) (all rows, col 1) A(end,:)

Operators

.* ./ .^ (element-wise) * (matrix mult)

Plotting

plot(x, y) xlabel('text') title('text')

Recursion Example: Matrix Determinant

function det_val = simple_recursive_determinant(matrix)
    % NOTE: This is a simplified example for a 3x3 matrix.
    [rows, ~] = size(matrix);
    
    % Base case: The determinant of a 2x2 matrix.
    if rows == 2
        det_val = matrix(1,1)*matrix(2,2) - matrix(1,2)*matrix(2,1);
        return;
    end
    
    % Recursive step (simplified for first element expansion)
    sub_matrix = matrix(2:end, 2:end);
    det_val = matrix(1,1) * simple_recursive_determinant(sub_matrix);
end

Scala

Quick Reference

Variables

val x = 10 (immutable) var y = 20 (mutable)

Functions

def name(param: Type): ReturnType = { }

Classes

class Name(val field: Type) { def method = { } }

Pattern Matching

x match { case pattern => result }

Collections

List(1, 2, 3) .map .filter .fold

Recursion Example: Topic Processor

object Course {
  def processTopics(topics: List[String]): Unit = topics match {
    // Base case: The list of topics is empty.
    case Nil => println("All topics processed.")
    
    // Recursive step: Process the head and recur on the tail.
    case head :: tail =>
      println(s"Processing: $head")
      processTopics(tail)
  }

  def main(args: Array[String]): Unit = {
    val moduleTopics = List("Scheme", "Prolog", "OOP")
    processTopics(moduleTopics)
  }
}

Perl

Quick Reference

Variables

$scalar @array %hash

Subroutines

sub name { my ($param) = @_; }

Arrays

push @arr, $val; pop @arr; shift unshift

Regex

$str =~ /pattern/; $str =~ s/old/new/;

File I/O

open(my $fh, '<', $file); while (<$fh>) { }

Recursion Example: Log File Parser

sub parse_log_file {
    my ($line_number) = @_;

    # Base case: We've reached the end of the log snippet.
    if ($line_number > 3) {
        print "Log file parsed.\n";
        return;
    }

    # Recursive step: Print a log line and move to the next.
    print "Parsing log line $line_number...\n";
    parse_log_file($line_number + 1);
}

parse_log_file(1);

Bash

Quick Reference

Variables

VAR="value" $VAR or ${VAR} (no spaces!)

Functions

function_name() { commands; }

Arguments

$1, $2, ... $@ (all args) $# (count)

Conditionals

if [[ condition ]]; then fi -eq -ne -lt -gt (numbers) = != (strings)

Loops

for i in {1..10}; do done while [[ condition ]]; do done

Recursion Example: Project File Organizer

#!/bin/bash

organize_project_files() {
    local level=$1
    local prefix=$2

    # Base case: Stop creating directories after a certain depth.
    if [[ $level -le 0 ]]; then
        return
    fi

    # Recursive step: Create a directory and then create a sub-directory.
    local dir_name="${prefix}_level_${level}"
    mkdir "$dir_name"
    echo "Created directory: $dir_name"
    cd "$dir_name"
    organize_project_files $((level - 1)) "sub"
    cd ..
}

organize_project_files 2 "module"