UP | HOME

Functions and Recursion
COP-3223H

Table of Contents

What is a function in C?

  • Named computation

There are languages with anonymous functions as well.

Abstraction

Replace a chunk of code with a name.

Define it in terms of its input and output.

Allows us to think and reason about the whole computation a function does as one, instead of all of its individual computational steps.

Benefits

  • Reuse
  • Organization
  • Abstraction

Naming a chunk of code

We can name code, i.e., define a function by wrapping it in curly braces:

myfunction() {
  printf("hello, world!\n");
  printf("1 + 1 = %d\n", 1 + 1);
}

We can use, i.e., call a function that code by writing the name:

int main(int argc, char **argv) {
  myfunction();  // call the function
}

In C, parentheses are used for both the function definition and call.

They can optionally take arguments for the inputs (and outputs in C) of the code snippet.

Notice that main itself is also a function. It is called by the operating system when your program is run, which is why we put the code we'd like to run first there.

Reuse

Functions allow reuse without having to copy code

int main(int argc, char **argv) {
  myfunction();
  myfunction();
  myfunction();
}

Reuse with specialization

What if a snippet of code uses a variable?

myfactorial() {
  int product = 1;
  // n is defined somewhere else
  for (int i = 1; i <= n; i++) {
    product = product * i;
  }
  printf("product = %d\n", product);
}

We still want to be able to define a function without having to define all the variables is uses. This allows for the function to generalize beyond a single computation.

Functions can take inputs

We can declare special variables (called arguments or parameters) for the inputs

myfactorial(int n) {
  int product = 1;
  for (int i = 1; i <= n; i++) {
    product = product * i;
  }
  printf("product = %d\n", product);
}

Declare the special input variables in between the parentheses.

Give functions inputs when calling them

Giving the input is called passing arguments:

int main(int argc, char **argv) {
  myfactorial(3);
  myfactorial(5);
  myfactorial(2);
}

Functions can produce an output

// prefix name with the type of the return
int myfactorial(int n) {
  int product = 1;
  for (int i = 1; i <= n; i++) {
    product = product * i;
  }
  // use the return keyword to specify the output
  return product;
}

In C, the arguments can also be used to specify outputs by passing arguments by reference. This can be seen later when introducing pointers.

Using function output

The function can be used in expressions

int main(int argc, char **argv) {
  int result = myfactorial(5) + 10;

  printf("%d\n", result);
}

Think of the call like a variable, where it is replaced with it's value before the expression is computed.

Function call semantics

  1. Evaluate each parameter to get a single value
  2. Assign that value to the definition's parameter variable
  3. Branch to the function's code and run
  4. On return, branch back to the calling function
  5. Replace the function call with the return value

Another example: exponent function

int exponent(int x, int e);

Multiple parameters delimited by comma

Using the abstraction

We can write code that uses a function before its implemented

int exponent(int x, int e);

int main(int argc, char **argv) {
  int a = 3;
  int b = 4;
  int csquared;

  csquared = exponent(a, 2) + exponent(b, 2);

  printf("csquared: %d\n", csquared);
}

The code won't run, but this shows the benefits of the function abstraction. We can ignore the low-level details of how exponent works, and focus instead on the code for the Pythagorean theorem.

Implementing exponent

int exponent(int x, int e) {
  int result = 1;
  for (int i = 0; i < e; i++) {
    result = result * x;
  }
  return result;
}

int main(int argc, char **argv) {
  int a = 3;
  int b = 4;
  int csquared;

  csquared = exponent(a, 2) + exponent(b, 2);

  printf("csquared: %d\n", csquared);
}

Delimit multiple parameters with a comma.

(Diagram illustrating the semantics of the function call)

  1. Evaluate each parameter to get a single value
  2. Assign that value to the definition's parameter variable
  3. Branch to the function's code and run
  4. On return, branch back to the calling function
  5. Replace the function call with the return value

Building up abstractions

int exponent(int x, int e) {
  int result = 1;
  for (int i = 0; i < e; i++) {
    result = result * x;
  }
  return result;
}

int square(int x) {
  return exponent(x, 2);
}

int main(int argc, char **argv) {
  int a = 3;
  int b = 4;
  int csquared;

  csquared = square(a) + square(b);

  printf("csquared: %d\n", csquared);
}

(Diagram illustrating the semantics of the function call)

  1. Evaluate each parameter to get a single value
  2. Assign that value to the definition's parameter variable
  3. Branch to the function's code and run
  4. On return, branch back to the calling function
  5. Replace the function call with the return value

void functions

void is used when functions take either no input or output (or both)

void print_int(int x) {
  printf("%d\n", x);
}
int read_int(void) {
  int x;
  scanf("%d", &x);
  return x;
}

int is the default output type of functions

Combining abstractions: struct and functions

  • struct creates new data types
  • functions declare input and output types
struct point {
  int x;
  int y;
};

struct point shift_up(struct point p) {
  p.x = p.x + 1;
  return p;
}

chase with sprites

Add sprite to struct

int sprite_width = 3;
int sprite_height = 3;
struct character {
  int state;
  int x;
  int y;
  char sprite[3][3];
};

draw sprite function

void draw_character(struct character c) {
  for (int j = 0; j < sprite_height; j++) {
    printf("\033[%d;%dH", c.y + j, c.x);
    for (int i = 0; i < sprite_width; i++) {
      putchar(c.sprite[j][i]);
    }
  }
}

copy sprite function

void copy_sprite(char tosprite[3][3], char fromsprite[3][3]) {
  for (int j = 0; j < sprite_height; j++) {
    for (int i = 0; i < sprite_width; i++) {
      tosprite[j][i] = fromsprite[j][i];
    }
  }
}

Full game

#include <stdio.h>
#include <stdbool.h>

#include "term.c"


int sprite_width = 3;
int sprite_height = 3;
struct character {
  int state;
  int x;
  int y;
  char sprite[3][3];
};

void copy_sprite(char tosprite[3][3], char fromsprite[3][3]) {
  for (int j = 0; j < sprite_height; j++) {
    for (int i = 0; i < sprite_width; i++) {
      tosprite[j][i] = fromsprite[j][i];
    }
  }
}

void draw_character(struct character c) {
  for (int j = 0; j < sprite_height; j++) {
    printf("\033[%d;%dH", c.y + j, c.x);
    for (int i = 0; i < sprite_width; i++) {
      putchar(c.sprite[j][i]);
    }
  }
}

int main(int argc, char **argv) {
  set_input_mode ();
  printf("\033[?25l"); // hide cursor

  int width = 40;
  int height = 20;

        char player_sprite[3][3] = { { 'o', ' ', 'o' },
                                                                                                                         { ' ', 'v', ' ' },
                                                                                                                         { '\\', '_', '/' } };

  // player state
  enum { vulnerable, invincible, dead };
  // player character
  struct character player;
  player.state = vulnerable;
  player.x = width / 2;
  player.y = height / 2;
  copy_sprite(player.sprite, player_sprite);

        char enemy_sprite[3][3] =  { { '\\', ' ', '/' },
                                                                                                                         { 'o', ' ', 'o' },
                                                                                                                         { ' ', '-', ' ' } };

  // enemy state
  enum { chasing, running, defeated };
  // enemy character
  struct character enemy;
  enemy.state = chasing;
  enemy.x = 1;
  enemy.y = 2;
  copy_sprite(enemy.sprite, enemy_sprite);

        char potion_sprite[3][3] = { { 'w', 'w', ' ' },
                                                                                                                         { '|', '|', ' ' },
                                                                                                                         { '/', '\\', ' ' } };

  // potion state
  enum { available, using, done };
  // potion character
  struct character potion;
  potion.state = available;
  potion.x = 29;
  potion.y = 11;
  copy_sprite(potion.sprite, potion_sprite);

  int potion_counter = 0;
  int random = 1;

  while (1) {
    printf("\x1b[2J");
    printf("\x1b[H");

    // draw
    switch (potion.state) {
    case available:
      draw_character(potion);
                        break;
    case using:
      // intentionally empty: don't draw it
      break;
    default:
      // do nothing
      break;
    }

    switch (enemy.state) {
    case chasing: // case 0:
      draw_character(enemy);
      break;
    case running: // case 1:
      draw_character(enemy);
      break;
    case defeated: // case 2:
      printf("\x1b[Hyou win");
      break;
    }

    switch (player.state) {
    case vulnerable:
      draw_character(player);
      break;
    case invincible:
      draw_character(player);
      break;
    case dead:
      printf("\x1b[Hyou lose");
      break;
    }


    // input
    int dx = 0;
    int dy = 0;
    int valid = 1;
    do {
      valid = 1;
      char c;
      scanf("%c", &c);
      switch (c) {
      case 'i':
        dy = -2;
        break;
      case 'k':
        dy = 2;
        break;
      case 'j':
        dx = -2;
        break;
      case 'l':
        dx = 2;
        break;
      default:
        valid = 0;
        break;
      }
    } while (! valid);



    // state updates

    switch (player.state) {
    case vulnerable:
      player.x += dx;
      player.y += dy;

      // collision will be checked in enemy state transition
      break;
    case invincible:
      player.x += dx;
      player.y += dy;

      // check for enemy collision
      if ((enemy.x - 1 <= player.x) && (player.x <= enemy.x + 1) &&
          (enemy.y - 1 <= player.y) && (player.y <= enemy.y + 1)) {
        player.state = vulnerable;
        enemy.state = defeated;
        potion.state = done;
      }
      break;
    }

    switch (enemy.state) {
    case chasing:
      // get closer
      if (player.x > enemy.x) {
        enemy.x += 1;
      }
      if (player.x < enemy.x) {
        enemy.x -= 1;
      }
      if (player.y > enemy.y) {
        enemy.y += 1;
      }
      if (player.y < enemy.y) {
        enemy.y -= 1;
      }

      // check player collision
      // check for collision
      if ((player.x == enemy.x || player.x == enemy.x + 1) &&
          (player.y == enemy.y || player.y == enemy.y + 1)) {
        player.state = dead;
      }
      break;
    case running:
      // get farther
      if (player.x > enemy.x) {
        enemy.x -= 1;
      }
      if (player.x < enemy.x) {
        enemy.x += 1;
      }
      if (player.y > enemy.y) {
        enemy.y -= 1;
      }
      if (player.y < enemy.y) {
        enemy.y += 1;
      }
      if (enemy.x < 0) {
        enemy.x = 0;
      }
      if (enemy.x > width) {
        enemy.x = width;
      }
      if (enemy.y < 0) {
        enemy.y = 0;
      }
      if (enemy.y > height) {
        enemy.y = height;
      }
      break;
    case defeated:
      // do nothing
      break;
    }

    switch (potion.state) {
    case available:
      if ((player.x == potion.x || player.x == potion.x + 1) &&
          (player.y == potion.y || player.y == potion.y + 1)) {
        player.state = invincible;
        enemy.state = running;
        potion.state = using;
        potion_counter = 10;
      }
      break;
    case using:
      // while using, decrement potion_counter
      potion_counter -= 1;
      if (potion_counter == 1) {
        potion.state = available;
        player.state = vulnerable;
        enemy.state = chasing;
        random = (random * 97) % 65533;
        potion.x = random % width;
        random = (random * 97) % 65533;
        potion.y = random % height;
      }
      break;
    case done:
      // do nothing
      break;
    }
  }

}

Functions have their own (local) variables

int g(int x) {
  x = x + 1;
  return x;
}

int main(int argc, char **argv) {
  int x = 1;
  g(x);
  printf("%d\n", x);
}

This is connected to the scoping rules we learned about when talking about for loops.

Functions for iteration

int sum = 0;
for (int i = 1; i <= 3; i++) {
  sum = sum + i;
}
int sum3() {
  return sum2() + 3;
}

int sum2() {
  return sum1() + 2;
}

int sum1() {
  return sum0() + 1;
}

int sum0() {
  return 0;
}
  • Abstract away one step (the body) of the for loop
  • Last function (sum0) is like the initializer
  • The rest (sumX) of the functions follow a pattern

What if we could "generate" these functions based on a pattern?

This is what functions with parameters and their own local variables allows for.

Function calls "generate" new instance

Each call creates new copy of the functions variables, including the parameter.

This is called the recursive step

Take a specific function instance

int sum3() {
  return sum2() + 3;
}

Paramterize what's different about each function

int sum(3) {
  return sum(2) + 3;
}

Then generalize the pattern with the parameter

int sum(int n) {
  return sum(n - 1) + n;
}

What happens when we call this function?

Recursive calls are like iteration

The call is a goto back to the top of the function.

In the function call semantics this is like iterating back to step 1 repeated until a conditional code path stops the iteration.

Stopping the iteration

The last call is called the base case

int sum1() {
  return sum0() + 1;
}

int sum0() {
  return 0;
}

Encoding the last step (base case)

int sum0() {
  return 0;
}

int sum(0) {
  return 0;
}

int sum(int n) {
  return 0; // when n is 0
}

Combining recursive step and base case

How do we combine these two functions into one?

int sum(int n) {
  // recursive step
  return sum(n - 1) + n;
}
int sum(int n) {
  // base case
  return 0; // when n is 0
}

The base case only happens when n is 0. We can use a conditional to check for this.

When n is greater than 0

int sum(int n) {
  // recursive step
  return sum(n - 1) + n;
}

When n is 0

int sum(int n) {
  // base case
  return 0; // when n is 0
}

Use a condition inside a shared function instead of around the functions

The complete recursive function

int sum(int n) {
  // recursive step
  if (n > 0) {
    return sum(n - 1) + n;

  // base case
  } else if (n == 0) {
    return 0; // when n is 0

  // should not happen
  } else {
    assert(false);
  }
}

Diagram of the function calls

Lay out each copy of local variables that each function call has

Point out that it's a stack

Factorial with recursion

int factorial(int n) {
  if (n > 0) {
    return factorial(n - 1) * n;
  } else if (0 == n) {
    return 1;
  } else {
    assert(false);
  }
}

Eight queens

The eight queens puzzle

(Diagram)

The for loop project was to create the eiqht queens game, where the user could only place queens in legal positions.

In this exercise, we will show how to automatically solve the puzzle, using recursion.

Solution strategy

  • Naive approach: try every possibility
  • Try one queen in every row
  • If we fail, go back and try the next column
  • Recursion with backtracking
    • Recursive step: given X queens, place one more
      • If no solution works, go back to X - 1 and try more solutions (backtracking)
    • Base case: got all rows (or had to backtrack)

Simplified stepwise refinement

init the board
place row 0

place the next row
if we're done, draw it
otherwise
  try each column in the row
    place a queen if safe, then place the next row

Backtracking made explicit

init the board
place row 0

place row X
if we're done, draw it
otherwise
  try each column in the row
    if column is safe
      place a queen
      check the next row X + 1
      unplace a queen (so we can keep trying)

An implementation in C

#include <stdio.h>
#include <assert.h>
#include <stdbool.h>

void draw(int board[8]) {
  printf("  ");
  for (int j = 0; j < 8; j++) {
    printf("%d", j);
  }
  putchar('\n');
  for (int i = 0; i < 8; i++) {
    printf("%d ", i);
    for (int j = 0; j < 8; j++) {
      if (board[i] == j) {
        putchar('Q');
      } else {
        putchar('.');
      }
    }
    putchar('\n');
  }
  putchar('\n');
  putchar('\n');
}

int safe(int board[8], int i, int j) {
  // no need to check columns, we only add one queen per row anyway
  /* for (int col = 0; col < 8; col++) { */
  /* 	if (board[i] == col) { */
  /* 		return false; */
  /* 	} */
  /* } */
  // check the column
  for (int row = 0; row < 8; row++) {
    if (board[row] == j) {
      return false;
    }
  }
  // check each diagonal the brute force way. wirth has a clever
  // optimization that makes the observation that position with the
  // same difference or sum of the row, col indices means there is a
  // queen in that position.  it requires holding two additional
  // arrays and setting/unsetting them in addition to the board
  for (int row = i, col = j; (row < 8) && (col < 8); row++, col++) {
    if (board[row] == col) {
      return false;
    }
  }
  for (int row = i, col = j; (row < 8) && (col >= 0); row++, col--) {
    if (board[row] == col) {
      return false;
    }
  }
  for (int row = i, col = j; (row >= 0) && (col < 8); row--, col++) {
    if (board[row] == col) {
      return false;
    }
  }
  for (int row = i, col = j; (row >= 0) && (col >= 0); row--, col--) {
    if (board[row] == col) {
      return false;
    }
  }
  return true;
}

void place(int board[8], int i) {
  if (8 == i) {
    // if we're on the last row, it means we've found a solution
    draw(board);
  }
  for (int j = 0; j < 8; j++) {
    // try each column in the candidate row
    if (safe(board, i, j)) {
      // if the column is safe, place a queen
      board[i] = j;
      // then try placing a queen in the next row
      place(board, i + 1);
      // unplace the queen and keep trying columns
      board[i] = -1;
    }
  }
}

int main(int argc, char **argv) {
  int board[8];

  // init board
  for (int i = 0; i < 8; i++) {
    board[i] = -1;
  }

  // try starting in each column in the first row
  for (int j = 0; j < 8; j++) {
    board[0] = j;
    place(board, 1);
  }
}

Author: Paul Gazzillo

Created: 2026-11-09 Mon 10:15

Validate