<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Vibe Coding Forem: Ositadinma Divine</title>
    <description>The latest articles on Vibe Coding Forem by Ositadinma Divine (@dositadi).</description>
    <link>https://vibe.forem.com/dositadi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3662051%2Fe1f83455-2a1f-4800-94ab-56efed2b5f6b.jpg</url>
      <title>Vibe Coding Forem: Ositadinma Divine</title>
      <link>https://vibe.forem.com/dositadi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://vibe.forem.com/feed/dositadi"/>
    <language>en</language>
    <item>
      <title>Structs and Custom Data Types</title>
      <dc:creator>Ositadinma Divine</dc:creator>
      <pubDate>Sun, 25 Jan 2026 00:43:25 +0000</pubDate>
      <link>https://vibe.forem.com/dositadi/structs-and-custom-data-types-331h</link>
      <guid>https://vibe.forem.com/dositadi/structs-and-custom-data-types-331h</guid>
      <description>&lt;p&gt;Go offers a powerful way to define custom data types using structs, which allow grouping related data fields together to form a single, coherent unit. This enhances code organization, readability, and maintainability by enabling you to model real-world entities directly within your programs. Structs are fundamental for building scalable web services as they provide the foundation for representing complex data, such as API request/response bodies, database records, and configuration settings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Defining Structs&lt;/strong&gt;&lt;br&gt;
A struct is a collection of fields (variables) of potentially different data types grouped together under a single name. You define a struct using the type keyword, followed by the struct's name and the struct keyword, enclosing its fields within curly braces {}.&lt;/p&gt;

&lt;p&gt;Each field within a struct has a name and a data type. It is good practice to start field names with an uppercase letter if you want them to be accessible outside the package (exported), or a lowercase letter if they should only be accessible within the package (unexported). This concept of exportability is crucial in Go for controlling visibility.&lt;/p&gt;

&lt;p&gt;`package main&lt;/p&gt;

&lt;p&gt;import "fmt"&lt;/p&gt;

&lt;p&gt;// User represents a user profile in our system.&lt;br&gt;
// It groups related information like ID, Name, and Email.&lt;br&gt;
type User struct {&lt;br&gt;
    ID    int&lt;br&gt;
    Name  string&lt;br&gt;
    Email string&lt;br&gt;
    // IsActive is unexported, meaning it's only accessible within the 'main' package.&lt;br&gt;
    isActive bool&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// Product represents an item available for purchase.&lt;br&gt;
type Product struct {&lt;br&gt;
    ProductID   string&lt;br&gt;
    Name        string&lt;br&gt;
    Description string&lt;br&gt;
    Price       float64&lt;br&gt;
    Quantity    int&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;func main() {&lt;br&gt;
    // Creating an instance of User&lt;br&gt;
    var user1 User&lt;br&gt;
    fmt.Println("Default User:", user1) // Fields will have their zero values (0 for int, "" for string, false for bool)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Initializing a struct with field values
user2 := User{
    ID:    1,
    Name:  "Alice Wonderland",
    Email: "alice@example.com",
    isActive: true, // Assigning value to unexported field
}
fmt.Println("User 2:", user2)

// Initializing a struct without field names (order matters)
// This approach is less readable and prone to errors if struct field order changes.
user3 := User{2, "Bob The Builder", "bob@example.com", false}
fmt.Println("User 3:", user3)

// Accessing individual fields
fmt.Println("User 2 Name:", user2.Name)
fmt.Println("User 3 ID:", user3.ID)

// Modifying fields
user2.Email = "alice.w@newdomain.com"
fmt.Println("User 2 updated Email:", user2.Email)

// Example with Product struct
laptop := Product{
    ProductID:   "LAPTOP-001",
    Name:        "UltraBook Pro",
    Description: "Lightweight and powerful laptop",
    Price:       1299.99,
    Quantity:    10,
}
fmt.Println("Product:", laptop)
fmt.Println("Laptop Price:", laptop.Price)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Zero Values of Structs&lt;/strong&gt;&lt;br&gt;
When a struct variable is declared but not explicitly initialized, its fields automatically take on their respective zero values. For example, int fields default to 0, string fields to "" (empty string), and bool fields to false. This behavior is consistent across Go's data types and helps prevent uninitialized data errors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Struct Field Tags&lt;/strong&gt;&lt;br&gt;
Struct field tags are small string literals associated with each field in a struct. They provide metadata about the field, which can be used by various Go packages, particularly for encoding/decoding data (like JSON or XML) or for database mapping. Tags are defined using backticks (`) after the field's type.&lt;/p&gt;

&lt;p&gt;A common use case is defining how a struct field should be represented when marshaling to JSON or unmarshaling from JSON. The json:"fieldName" tag specifies the JSON key name. The omitempty option in a JSON tag indicates that the field should be omitted from the JSON output if its value is the zero value for its type.&lt;/p&gt;

&lt;p&gt;`package main&lt;/p&gt;

&lt;p&gt;import (&lt;br&gt;
    "encoding/json"&lt;br&gt;
    "fmt"&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;// APIUser represents a user profile for API interactions.&lt;br&gt;
// Tags are used to control JSON serialization/deserialization.&lt;br&gt;
type APIUser struct {&lt;br&gt;
    ID        int    &lt;code&gt;json:"id"&lt;/code&gt;&lt;br&gt;
    Username  string &lt;code&gt;json:"username"&lt;/code&gt;&lt;br&gt;
    Email     string &lt;code&gt;json:"email,omitempty"&lt;/code&gt; // omitempty will skip if Email is ""&lt;br&gt;
    IsAdmin   bool   &lt;code&gt;json:"is_admin"&lt;/code&gt;&lt;br&gt;
    CreatedAt string &lt;code&gt;json:"created_at"&lt;/code&gt; // Example: storing creation time as a string for simplicity&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;func main() {&lt;br&gt;
    user := APIUser{&lt;br&gt;
        ID:        101,&lt;br&gt;
        Username:  "johndoe",&lt;br&gt;
        Email:     "&lt;a href="mailto:john.doe@example.com"&gt;john.doe@example.com&lt;/a&gt;",&lt;br&gt;
        IsAdmin:   false,&lt;br&gt;
        CreatedAt: "2023-01-15T10:00:00Z",&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Marshal the struct to JSON
jsonData, err := json.MarshalIndent(user, "", "  ") // Use MarshalIndent for pretty printing
if err != nil {
    fmt.Println("Error marshaling JSON:", err)
    return
}
fmt.Println("User JSON with email:")
fmt.Println(string(jsonData))

// Create another user with an empty email to demonstrate omitempty
userWithoutEmail := APIUser{
    ID:        102,
    Username:  "janedoe",
    Email:     "", // This field will be omitted due to "omitempty" tag
    IsAdmin:   true,
    CreatedAt: "2023-01-16T11:30:00Z",
}

jsonDataWithoutEmail, err := json.MarshalIndent(userWithoutEmail, "", "  ")
if err != nil {
    fmt.Println("Error marshaling JSON:", err)
    return
}
fmt.Println("\nUser JSON without email (omitempty in effect):")
fmt.Println(string(jsonDataWithoutEmail))

// Demonstrate unmarshaling JSON into a struct
jsonString := `
{
    "id": 103,
    "username": "peterg",
    "email": "peter.g@example.com",
    "is_admin": true,
    "created_at": "2023-01-17T14:45:00Z"
}`

var newUser APIUser
err = json.Unmarshal([]byte(jsonString), &amp;amp;newUser) // &amp;amp;newUser is important (pointer)
if err != nil {
    fmt.Println("Error unmarshaling JSON:", err)
    return
}
fmt.Println("\nUnmarshaled User:", newUser)
fmt.Println("Unmarshaled User Username:", newUser.Username)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;In the json:"email,omitempty" tag, json is the tag key, "email" is the value that specifies the JSON field name, and omitempty is an option that tells the json package to omit the field if its value is the zero value for its type (e.g., empty string for string, 0 for int, false for bool, nil for pointers or slices).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Anonymous Structs&lt;/strong&gt;&lt;br&gt;
Anonymous structs are structs defined without a name. They are typically used for temporary, one-off data structures where defining a full type definition might be overkill. This is useful when you need to group a few fields together for a very specific, local purpose, like defining a temporary configuration object or a response structure within a function.&lt;/p&gt;

&lt;p&gt;`package main&lt;/p&gt;

&lt;p&gt;import (&lt;br&gt;
    "fmt"&lt;br&gt;
    "encoding/json"&lt;br&gt;
)&lt;/p&gt;

&lt;p&gt;func main() {&lt;br&gt;
    // Anonymous struct used for a temporary configuration&lt;br&gt;
    config := struct {&lt;br&gt;
        Host string&lt;br&gt;
        Port int&lt;br&gt;
        Debug bool&lt;br&gt;
    }{&lt;br&gt;
        Host: "localhost",&lt;br&gt;
        Port: 8080,&lt;br&gt;
        Debug: true,&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fmt.Printf("Server Config: Host=%s, Port=%d, Debug=%t\n", config.Host, config.Port, config.Debug)

// Another anonymous struct, perhaps for a simple log entry
logEntry := struct {
    Timestamp string `json:"timestamp"`
    Message   string `json:"message"`
    Level     string `json:"level"`
}{
    Timestamp: "2023-10-26T10:30:00Z",
    Message:   "Application started successfully",
    Level:     "INFO",
}

fmt.Printf("Log Entry: %s - %s [%s]\n", logEntry.Timestamp, logEntry.Level, logEntry.Message)

// Anonymous struct for a JSON response payload
// Notice the JSON tags for proper serialization
responsePayload := struct {
    Status  string `json:"status"`
    Code    int    `json:"code"`
    Message string `json:"message"`
}{
    Status:  "success",
    Code:    200,
    Message: "Operation completed",
}

jsonResponse, err := json.MarshalIndent(responsePayload, "", "  ")
if err != nil {
    fmt.Println("Error marshaling JSON:", err)
    return
}
fmt.Println("\nAnonymous Struct as JSON Response:")
fmt.Println(string(jsonResponse))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;Anonymous structs are particularly handy when you're dealing with one-off data structures, for example, creating a specific JSON response body or a temporary data container in a function. Their scope is limited to where they are defined.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nested Structs and Struct Embedding&lt;/strong&gt;&lt;br&gt;
Structs can contain other structs as fields. This allows for creating complex data structures by composing smaller, more manageable structs. This is known as nested structs.&lt;/p&gt;

&lt;p&gt;Go also supports struct embedding, which is a powerful mechanism for composition. When you embed a struct (or an interface, which will be covered in a later lesson) into another struct, the fields and methods (methods will be covered in the next lesson) of the embedded struct are promoted to the outer struct. This effectively means you can access the fields of the embedded struct directly through the outer struct's instance, as if they were fields of the outer struct itself. This promotes code reuse and can simplify data modeling.&lt;/p&gt;

&lt;p&gt;Nested Structs&lt;br&gt;
With nested structs, you access the inner struct's fields using a dot notation chain.&lt;/p&gt;

&lt;p&gt;`package main&lt;/p&gt;

&lt;p&gt;import "fmt"&lt;/p&gt;

&lt;p&gt;// Address defines a postal address.&lt;br&gt;
type Address struct {&lt;br&gt;
    Street  string&lt;br&gt;
    City    string&lt;br&gt;
    ZipCode string&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// ContactInfo defines contact details.&lt;br&gt;
type ContactInfo struct {&lt;br&gt;
    Email string&lt;br&gt;
    Phone string&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// Customer represents a customer with an associated address and contact info.&lt;br&gt;
type Customer struct {&lt;br&gt;
    ID        int&lt;br&gt;
    Name      string&lt;br&gt;
    Shipping  Address     // Nested struct&lt;br&gt;
    Billing   Address     // Another nested struct of the same type&lt;br&gt;
    Contact   ContactInfo // Nested struct&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;func main() {&lt;br&gt;
    // Creating a Customer instance with nested structs&lt;br&gt;
    customer1 := Customer{&lt;br&gt;
        ID:   1001,&lt;br&gt;
        Name: "Global Tech Solutions",&lt;br&gt;
        Shipping: Address{&lt;br&gt;
            Street:  "123 Tech Avenue",&lt;br&gt;
            City:    "Innovation City",&lt;br&gt;
            ZipCode: "90210",&lt;br&gt;
        },&lt;br&gt;
        Billing: Address{&lt;br&gt;
            Street:  "456 Finance Street",&lt;br&gt;
            City:    "Capital Town",&lt;br&gt;
            ZipCode: "10001",&lt;br&gt;
        },&lt;br&gt;
        Contact: ContactInfo{&lt;br&gt;
            Email: "&lt;a href="mailto:info@globaltech.com"&gt;info@globaltech.com&lt;/a&gt;",&lt;br&gt;
            Phone: "555-123-4567",&lt;br&gt;
        },&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fmt.Println("Customer ID:", customer1.ID)
fmt.Println("Customer Name:", customer1.Name)
fmt.Println("Shipping Street:", customer1.Shipping.Street) // Accessing nested field
fmt.Println("Billing City:", customer1.Billing.City)
fmt.Println("Contact Email:", customer1.Contact.Email)

// Modifying a nested field
customer1.Shipping.Street = "789 Enterprise Blvd"
fmt.Println("Updated Shipping Street:", customer1.Shipping.Street)

// Printing the entire struct
fmt.Printf("Customer 1: %+v\n", customer1) // %+v prints struct field names
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Struct Embedding&lt;/strong&gt;&lt;br&gt;
With struct embedding, you simply declare the type of the struct you want to embed without providing a field name. The embedded struct's fields and methods are then directly accessible from the outer struct.&lt;/p&gt;

&lt;p&gt;`package main&lt;/p&gt;

&lt;p&gt;import "fmt"&lt;/p&gt;

&lt;p&gt;// Person represents basic personal information.&lt;br&gt;
type Person struct {&lt;br&gt;
    Name string&lt;br&gt;
    Age  int&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// Employee embeds Person, meaning an Employee "is a" Person.&lt;br&gt;
// It also has additional employee-specific fields.&lt;br&gt;
type Employee struct {&lt;br&gt;
    Person    // Embedded struct (no field name, just type)&lt;br&gt;
    EmployeeID string&lt;br&gt;
    Department string&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;// Developer also embeds Person, illustrating reuse.&lt;br&gt;
type Developer struct {&lt;br&gt;
    Person    // Embedded struct&lt;br&gt;
    Skills []string&lt;br&gt;
    Level string&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;func main() {&lt;br&gt;
    // Creating an Employee instance&lt;br&gt;
    emp1 := Employee{&lt;br&gt;
        Person: Person{ // Initialize the embedded struct&lt;br&gt;
            Name: "Maria Garcia",&lt;br&gt;
            Age:  30,&lt;br&gt;
        },&lt;br&gt;
        EmployeeID: "EMP007",&lt;br&gt;
        Department: "Engineering",&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Accessing fields of the embedded Person struct directly
fmt.Println("Employee Name:", emp1.Name) // Access Person's Name directly
fmt.Println("Employee Age:", emp1.Age)   // Access Person's Age directly
fmt.Println("Employee ID:", emp1.EmployeeID)
fmt.Println("Employee Department:", emp1.Department)

// Modifying an embedded field
emp1.Age = 31
fmt.Println("Updated Employee Age:", emp1.Age)

// Creating a Developer instance
dev1 := Developer{
    Person: Person{
        Name: "Leo Kim",
        Age:  25,
    },
    Skills: []string{"Go", "PostgreSQL", "Docker"},
    Level: "Junior",
}
fmt.Println("\nDeveloper Name:", dev1.Name)
fmt.Println("Developer Skills:", dev1.Skills)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}`&lt;/p&gt;

&lt;p&gt;When you embed Person into Employee, Employee automatically gains Name and Age fields. This is syntactic sugar; internally, Go treats it like a field named Person of type Person. If Employee also had a field named Name, the outer Employee.Name would take precedence, and you would access Person's Name via emp1.Person.Name. Embedding is a powerful tool for composition and achieving a form of inheritance-like behavior in Go without explicit inheritance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exercises&lt;/strong&gt;&lt;br&gt;
Complete the exercise to solidify your understanding of structs and custom data types.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Define and Initialize a Book Struct:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a struct named Book with the following fields: Title (string), Author (string), ISBN (string), Price (float64), and PublicationYear (int).&lt;br&gt;
Define a Book variable and initialize it using a struct literal, providing values for all fields.&lt;br&gt;
Print the Title and Author of your book.&lt;br&gt;
Modify the Price of your book and print the updated price.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>ai</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Building the Foundation: A Comprehensive Guide to Recursion (The Function That Calls Itself)</title>
      <dc:creator>Ositadinma Divine</dc:creator>
      <pubDate>Sat, 20 Dec 2025 21:35:51 +0000</pubDate>
      <link>https://vibe.forem.com/dositadi/building-the-foundation-a-comprehensive-guide-to-recursion-the-function-that-calls-itself-5e1d</link>
      <guid>https://vibe.forem.com/dositadi/building-the-foundation-a-comprehensive-guide-to-recursion-the-function-that-calls-itself-5e1d</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxlvkxi9hkevmppaqedfm.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxlvkxi9hkevmppaqedfm.jpeg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Recursion?‎&lt;/strong&gt;‎&lt;br&gt;
A function that calls itself again and again till a base condition is reached is called a recursive function. This method solves a problem by calling a copy of itself on a smaller unit of the problem being solved. Each call to itself is called a recursive step, however it is important that a recursive function terminates given a valid base case.‎&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Why Use Recursion in Problem Solving?‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiatim3k42unxnh37h0vf.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiatim3k42unxnh37h0vf.webp" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎Recursive code is generally shorter and easier to write than iterative code and most useful for tasks that can be broken down into similar subtasks examples includes&lt;br&gt;
‎a. Sorting&lt;br&gt;
‎b. Searching and,&lt;br&gt;
‎c. Tree traversals etc&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Format of a Recursive Function‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3mmjr8s31thrlfvwikf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3mmjr8s31thrlfvwikf.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A recursive function performs a task in part by calling itself to perform the subtasks. At some ‎point, the function encounters a subtask that it can perform without calling itself. Thus a recursive function can be sub divided into two parts.‎&lt;/p&gt;

&lt;p&gt;‎A. Base Case: the base case is the case where the function does not recur itself. A recursive function can have one or more base cases depending on the problem being solved.‎&lt;br&gt;
‎B. Recursive Case: this is the case where the function calls itself to ‎perform a subtask. A recursive function can also have more than one recursive cases depending on the problem being solved.‎&lt;/p&gt;

&lt;p&gt;‎All recursive functions can be written using the format below.‎&lt;/p&gt;

&lt;p&gt;‎&lt;em&gt;// base case(s)&lt;/em&gt;&lt;br&gt;
‎&lt;em&gt;If(test for base case 1)&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some base case value&lt;/em&gt;&lt;br&gt;
‎&lt;em&gt;Else if(test for another base case)&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some other base case value&lt;/em&gt;&lt;br&gt;
‎… …&lt;br&gt;
‎&lt;em&gt;// Recursive cases&lt;/em&gt;&lt;br&gt;
&lt;em&gt;‎Else&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some work and then a recursive call‎&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎How a Recursive function works‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fedxqqo0ijtbp28pfuzcd.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fedxqqo0ijtbp28pfuzcd.webp" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎We will talk through this using an example in this case considering a factorial function (n!)‎&lt;br&gt;
‎The factorial of a number (n) is the product of all positive integers between n and 1.‎&lt;br&gt;
‎Hence it's defined thus as‎&lt;/p&gt;

&lt;p&gt;‎0! = 1&lt;br&gt;
‎1! = 1&lt;br&gt;
‎2! = 2*1&lt;br&gt;
‎3! = 3*2*1&lt;br&gt;
‎4! = 4*3*2*1‎&lt;/p&gt;

&lt;p&gt;‎If we study the pattern we can say&lt;br&gt;
‎1! = 1 &lt;em&gt;(1–1) where (1–1) =0!&lt;br&gt;
‎2! = 2&lt;/em&gt;(2–1) where (2–1) =1!&lt;br&gt;
‎3! = 3*(3–1) where (3–1) =2!&lt;br&gt;
‎4! = 4*(4–1) where (4–1) =3!‎&lt;br&gt;
‎Thus the formula&lt;br&gt;
‎n! = n * (n- 1) if n &amp;gt; 0‎&lt;/p&gt;

&lt;p&gt;‎For the factorial problem, our base case is 0!, since 0! Will always be 1 and our recursive case is represented with the function f(n-1)‎&lt;br&gt;
‎If we transform this into a code we will have&lt;/p&gt;

&lt;p&gt;

&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;




&lt;p&gt;‎The code will be executed in the manner explained below:&lt;br&gt;
‎Recall that a recursive function calls a copy of itself for each subtasks, this copy is stored in a stack memory that uses the LIFO pattern‎. Lets say we want to find the factorial of the value 4, if you study the diagram below, you will get a clearer view of how a recursive function works.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83e7uu8w3m4ccak7ng69.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83e7uu8w3m4ccak7ng69.jpg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎Recursion and Memory‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvd4mhiajvb74g8q5gtih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvd4mhiajvb74g8q5gtih.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎Each recursive call makes a new copy of that method (actually only the variables) in memory. Once a method ends (that is, it returns some data), the copy of that returning method is removed from memory, however, If we get infinite recursion, the program may run out of memory and result in fatal stack overflow error. this is why a valid base case is always needed when considering to use a recursive algorithm to solve a problem.‎&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎Recursion versus Iteration‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ywarvdpah0lk34t2zyy.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ywarvdpah0lk34t2zyy.jpg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎While discussing recursion, the basic question that comes to mind is: which way is better? –iteration or recursion? The answer to this question depends on what you are trying to do. A recursive approach makes ‎it simpler to solve a problem that may not have the most obvious of answers. But, recursion adds overhead for each recursive call (it needs space on the stack memory).‎ &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recursion&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Recursion‎ ‎terminates when a base case is reached.&lt;/li&gt;
&lt;li&gt;‎Each recursive call requires extra space on the stack memory.&lt;/li&gt;
&lt;li&gt;‎If we get infinite recursion, the program may run out of memory and result in stack overflow.&lt;/li&gt;
&lt;li&gt;Solutions to some problems are easier to formulate recursively.‎&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;‎Iteration‎&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Terminates when a condition is proven to be false.&lt;/li&gt;
&lt;li&gt;‎Each iteration does not require extra space.&lt;/li&gt;
&lt;li&gt;An infinite loop could loop forever since there is no extra memory being created.&lt;/li&gt;
&lt;li&gt;‎Iterative solutions to a problem may not always be as obvious as a recursive olution.‎&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;‎Example of Algorithms that make use of Recursion‎&lt;br&gt;
‎1. Fibonacci, Factorial findings&lt;br&gt;
‎2. Merge sort, Quick sort&lt;br&gt;
‎3. Binary search&lt;br&gt;
‎4. Tree traversals and&lt;br&gt;
‎5. Graph traversals etc‎&lt;/p&gt;

&lt;p&gt;‎Dear reader, Kindly leave a comment or send me a mail, if you have any suggestions on the topic or possible improvements let's learn and grow together.‎&lt;/p&gt;

&lt;p&gt;‎If this article has benefited you in a way, don't forget to leave as much clap as u wish too, also feel free to follow for more articles, let's encourage ourselves‎.&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Dont forget to also check me out in my other social platforms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://x.com/dositadix.com" rel="noopener noreferrer"&gt;https://x.com/dositadix.com&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.linkedin.com/in/divine-ositadinma-69644539b" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/divine-ositadinma-69644539b&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dositadi.medium.com" rel="noopener noreferrer"&gt;https://dositadi.medium.com&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Building the Foundation: A Comprehensive Guide to Recursion (The Function That Calls Itself)</title>
      <dc:creator>Ositadinma Divine</dc:creator>
      <pubDate>Sat, 20 Dec 2025 20:30:33 +0000</pubDate>
      <link>https://vibe.forem.com/dositadi/building-the-foundation-a-comprehensive-guide-to-recursion-the-function-that-calls-itself-2jm8</link>
      <guid>https://vibe.forem.com/dositadi/building-the-foundation-a-comprehensive-guide-to-recursion-the-function-that-calls-itself-2jm8</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxlvkxi9hkevmppaqedfm.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxlvkxi9hkevmppaqedfm.jpeg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Recursion?‎&lt;/strong&gt;‎&lt;br&gt;
A function that calls itself again and again till a base condition is reached is called a recursive function. This method solves a problem by calling a copy of itself on a smaller unit of the problem being solved. Each call to itself is called a recursive step, however it is important that a recursive function terminates given a valid base case.‎&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Why Use Recursion in Problem Solving?‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiatim3k42unxnh37h0vf.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiatim3k42unxnh37h0vf.webp" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎Recursive code is generally shorter and easier to write than iterative code and most useful for tasks that can be broken down into similar subtasks examples includes&lt;br&gt;
‎a. Sorting&lt;br&gt;
‎b. Searching and,&lt;br&gt;
‎c. Tree traversals etc&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Format of a Recursive Function‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3mmjr8s31thrlfvwikf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fj3mmjr8s31thrlfvwikf.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A recursive function performs a task in part by calling itself to perform the subtasks. At some ‎point, the function encounters a subtask that it can perform without calling itself. Thus a recursive function can be sub divided into two parts.‎&lt;/p&gt;

&lt;p&gt;‎A. Base Case: the base case is the case where the function does not recur itself. A recursive function can have one or more base cases depending on the problem being solved.‎&lt;br&gt;
‎B. Recursive Case: this is the case where the function calls itself to ‎perform a subtask. A recursive function can also have more than one recursive cases depending on the problem being solved.‎&lt;/p&gt;

&lt;p&gt;‎All recursive functions can be written using the format below.‎&lt;/p&gt;

&lt;p&gt;‎&lt;em&gt;// base case(s)&lt;/em&gt;&lt;br&gt;
‎&lt;em&gt;If(test for base case 1)&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some base case value&lt;/em&gt;&lt;br&gt;
‎&lt;em&gt;Else if(test for another base case)&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some other base case value&lt;/em&gt;&lt;br&gt;
‎… …&lt;br&gt;
‎&lt;em&gt;// Recursive cases&lt;/em&gt;&lt;br&gt;
&lt;em&gt;‎Else&lt;/em&gt;&lt;br&gt;
‎ &lt;em&gt;return some work and then a recursive call‎&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎How a Recursive function works‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fedxqqo0ijtbp28pfuzcd.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fedxqqo0ijtbp28pfuzcd.webp" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎We will talk through this using an example in this case considering a factorial function (n!)‎&lt;br&gt;
‎The factorial of a number (n) is the product of all positive integers between n and 1.‎&lt;br&gt;
‎Hence it's defined thus as‎&lt;/p&gt;

&lt;p&gt;‎0! = 1&lt;br&gt;
‎1! = 1&lt;br&gt;
‎2! = 2*1&lt;br&gt;
‎3! = 3*2*1&lt;br&gt;
‎4! = 4*3*2*1‎&lt;/p&gt;

&lt;p&gt;‎If we study the pattern we can say&lt;br&gt;
‎1! = 1 &lt;em&gt;(1–1) where (1–1) =0!&lt;br&gt;
‎2! = 2&lt;/em&gt;(2–1) where (2–1) =1!&lt;br&gt;
‎3! = 3*(3–1) where (3–1) =2!&lt;br&gt;
‎4! = 4*(4–1) where (4–1) =3!‎&lt;br&gt;
‎Thus the formula&lt;br&gt;
‎n! = n * (n- 1) if n &amp;gt; 0‎&lt;/p&gt;

&lt;p&gt;‎For the factorial problem, our base case is 0!, since 0! Will always be 1 and our recursive case is represented with the function f(n-1)‎&lt;br&gt;
‎If we transform this into a code we will have&lt;/p&gt;

&lt;p&gt;

&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;




&lt;p&gt;‎The code will be executed in the manner explained below:&lt;br&gt;
‎Recall that a recursive function calls a copy of itself for each subtasks, this copy is stored in a stack memory that uses the LIFO pattern‎. Lets say we want to find the factorial of the value 4, if you study the diagram below, you will get a clearer view of how a recursive function works.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83e7uu8w3m4ccak7ng69.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F83e7uu8w3m4ccak7ng69.jpg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎Recursion and Memory‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvd4mhiajvb74g8q5gtih.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvd4mhiajvb74g8q5gtih.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎Each recursive call makes a new copy of that method (actually only the variables) in memory. Once a method ends (that is, it returns some data), the copy of that returning method is removed from memory, however, If we get infinite recursion, the program may run out of memory and result in fatal stack overflow error. this is why a valid base case is always needed when considering to use a recursive algorithm to solve a problem.‎&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;‎Recursion versus Iteration‎&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ywarvdpah0lk34t2zyy.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ywarvdpah0lk34t2zyy.jpg" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;‎While discussing recursion, the basic question that comes to mind is: which way is better? –iteration or recursion? The answer to this question depends on what you are trying to do. A recursive approach makes ‎it simpler to solve a problem that may not have the most obvious of answers. But, recursion adds overhead for each recursive call (it needs space on the stack memory).‎ &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Recursion&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Recursion‎ ‎terminates when a base case is reached.&lt;/li&gt;
&lt;li&gt;‎Each recursive call requires extra space on the stack memory.&lt;/li&gt;
&lt;li&gt;‎If we get infinite recursion, the program may run out of memory and result in stack overflow.&lt;/li&gt;
&lt;li&gt;Solutions to some problems are easier to formulate recursively.‎&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;‎Iteration‎&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Terminates when a condition is proven to be false.&lt;/li&gt;
&lt;li&gt;‎Each iteration does not require extra space.&lt;/li&gt;
&lt;li&gt;An infinite loop could loop forever since there is no extra memory being created.&lt;/li&gt;
&lt;li&gt;‎Iterative solutions to a problem may not always be as obvious as a recursive olution.‎&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;‎Example of Algorithms that make use of Recursion‎&lt;br&gt;
‎1. Fibonacci, Factorial findings&lt;br&gt;
‎2. Merge sort, Quick sort&lt;br&gt;
‎3. Binary search&lt;br&gt;
‎4. Tree traversals and&lt;br&gt;
‎5. Graph traversals etc‎&lt;/p&gt;

&lt;p&gt;‎Dear reader, Kindly leave a comment or send me a mail, if you have any suggestions on the topic or possible improvements let's learn and grow together.‎&lt;/p&gt;

&lt;p&gt;‎If this article has benefited you in a way, don't forget to leave as much clap as u wish too, also feel free to follow for more articles, let's encourage ourselves‎.&lt;/p&gt;

&lt;p&gt;‎&lt;strong&gt;Dont forget to also check me out in my other social platforms&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://x.com/dositadix.com" rel="noopener noreferrer"&gt;https://x.com/dositadix.com&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.linkedin.com/in/divine-ositadinma-69644539b" rel="noopener noreferrer"&gt;https://www.linkedin.com/in/divine-ositadinma-69644539b&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dositadi.medium.com" rel="noopener noreferrer"&gt;https://dositadi.medium.com&lt;/a&gt;&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>computerscience</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
