Creation and Use of Functions

(関数の作り方と使い方)

Computing Practice I

5th lecture, May 18, 2017

http://www.sw.it.aoyama.ac.jp/2017/CP1/lecture5.html

Martin J. Dürst

AGU

© 2005-17 Martin J. Dürst 青山学院大学

Today's Schedule

 

ミニテスト

 

Applications of C: Linux

 

Results of Previous Exercises

04A1 04A2 04A3 04B1 04B2 04C1
100 points 85 81 87 57 31 1
60 points 14 18 21 41 60 26
partial (10 points or more) - - - - - 46
partial (less than 10) - - - - - 14
error - - - - 3 7
not submitted - - - 1 5 5

 

Example Solutions for 04C1

 

Importance of Functions

 

Functions in Programming Languages and in Mathematics

 

Concepts and Terms around Functions

 

How to Think about Functions

Clearly separate thinking about:

 

Declarations and Definitions

Distinguished for functions (and global variables)

Attention: Our coursebook uses a lot of unnecessary declarations:

int main(void); // this declaration is unnecessary

int main(void)

{...

 

関数の抽出の手順

(Refactoring: Improving the Design of Existing Code, Martin Fowler et al., Addison-Wesley, 1999 の「メソッドの抽出より」)

 

Refactoring

 

A Function Calling Itself

Very simple example: Calculating the sum of integers from 1 to n (∑ni=0 i):

int sumN (int n)
{
if (n <= 0)
return 0;
else
return n + sumN(n-1);
}

Mathematical justification: ∑ni=0 i = n + ∑n-1i=0 i (for n>0); ∑0i=0 i = 0

 

Execution Example for sumN

Result: 6

 

Recursive Functions

 

One More Example of a Recursive Function

Convert a number i to n-ary representation:

void printNary (int i, int n) {
static char letters[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

if (i < n)
putchar (letters[i]);
else {
printNary (i/n, n);
putchar (letters[i%n]);
}
}

 

Execution Example for printNary

Result: 215

 

Important Points about Recursive Functions

 

Parts of a Recursive Function

  1. Non-recursive base case
  2. Actual recursion

 

Recursion Patterns

[recursion: recursive function call; processing: data processing local to the function]

 

プログラム開発のコツ

(advice for program development)

 

問題再利用の目的

 

演習問題の概要

空の関数、名前の無意味な関数などは減点対象

ヒント: 入力の関数の戻り値をうまく利用

(05C1 以外は全部非常に短い)

 

次回の準備

 

Glossary

function
関数
operating system
オペレーティングシステム
embedded device
組込機器
state machine
状態機械
function name
関数名
argument/parameter
引数 (ひきすう)
formal parameter
仮引数
actual parameter
実引数
return value
戻り値 (または返り値)
global variable
グローバル変数
side effect
副作用
(function) invocation
(関数の) 呼出
declaration
宣言
definition
定義
function extraction
関数の抽出
refactoring
リファクタリング
recursion
再帰
recursive function
再帰的関数
mathematical induction
数学的帰納法
stack overflow
スタック・オーバーフロー
tail recursion
末尾再帰
tower of Hanoi
ハノイの塔