• Tidak ada hasil yang ditemukan

chapter 9. Functions

N/A
N/A
Protected

Academic year: 2024

Membagikan "chapter 9. Functions"

Copied!
58
0
0

Teks penuh

(1)

민기복

Ki-Bok Min, PhD

서울대학교 에너지자원공학과 조교수

Assistant Professor, Energy Resources Engineering

Fundamentals of Computer System

- chapter 9. Functions

(2)

Last week

Chapter 7. C control statements: Branching and Jumps

• C control statements: Branching (분기)

– if, else : important! & Easy!

– Switch ~ case

• C control statements: Jumps

– Continue, break, goto

• Logical operators (논리연산자): && ||

• Character I/O functions (문자 입출력함수)

– getchar() and putchar()

(3)

if statement

three general forms

if (expression) statement

if (expression1) statement1

else if (expression2) statement2

else

statement3 if (expression)

statement1

else (expression2) statement2

(4)

if statement

general form (1)

if (expression) statement

• Branching statement (분기문)

• Test/execution is done only once

• while???

value > 0

printf (“양수입니다n”) if

false true

a single statement or a single block with { }

(5)

if statement

general form (2)

if (expression) statement1 else (expression)

statement2

value > 0

printf (“양수입니다n”) if

true else

printf (“음수입니다.\n”)

(6)

if statement

general form (3)

if (expression1) statement1

else if (expression2) statement2

else

statement3

value > 0

printf (“양수입니다n”) if

true else if

printf (“음수입니다.\n”) value < 0

true else

printf (“0입니다.\n”)

(7)

if statement

general form (3)

(8)

if statement

general form (3)

if (score < 1000) bonus = 0;

else if (score < 1500) bonus = 1;

else if (score < 2000) bonus = 2;

else if (score < 2500) bonus = 3;

else

bonus = 4;

Multiple levels up to 127

(9)

if statement

pairing else with if

if (number > 6)

if (number <12)

printf(“You are close!\n”);

else

printf(“Sorry, you lose a turn!\n”);

• When number is 5???

• Very important to have proper indentations (띄어쓰기)!

(10)

Character I/O functions ( 문자입출력함수 ) getchar() & putchar() - 단일문자

• getchar()

– returns the next character from input (입력으로부터 다음 문자를 리턴)

– No argument

– ch = getchar();  scanf(“%c, &ch);

• putchar()

– prints its argument.

– putchar(ch);  printf(“%c”, ch);

(11)

Logical operator

&& || !

Operator Meaning

&& And

|| Or

! Not

X Y X && Y X || Y X !

T T T T F

T F F T F

F T F T T

F F F F T

(12)

Logical operator

order of evaluation and range

if (range >= 90 && range <= 100 ) printf(“A\n”);

if (90<= range <= 100 ) printf(“A\n”);

Semantic error!

(90<= range) <= 100 always true Don’t do this!

0 or 1

(13)

Conditional operator ( 조건연산자 )

?:

• ?: the only tertiary operator (삼항연산자)

• General form

Expression1 ? Expression2 : Expression 3 ex) max = (a > b) ? a : b;

x = (y < 0) ? –y : y;

If (y<0) x = -y;

elsex = y;



true false

(14)

Loop Aids: Continue and break

• 처리의 순서나 흐름을 조절하는 제어문

• continue: 해당루프의 나머지를 건너뛰고, 해당

루프의 다음 사이클을 시작.

• break: 어떤 처리의 순서나 흐름을 중단하고, 루프를

탈출.

• 중첩구조에서는 내부구조만 영향을 받음.

(15)

Continue and break

while (( ch = getchar() ) ! EOF) {

blabla(ch);

if (ch == ‘\n’) break;

yakyak(ch);

}

blunder(n,m);

while (( ch = getchar() ) ! EOF) {

blabla(ch);

if (ch == ‘\n’)

continue yakyak(ch);

}

blunder(n,m);

(16)

Multiple choices: switch ~ case

switch (integer expression) {

case constant1:

statement1;

case constant2:

statement2;

default:

statements;

}

• expression & case label : integer (including char)

• No case label matches expression: default

(17)

Multiple choices: switch ~ case

Switch~case with break

Switch~case without break

(18)

Multiple choices: switch ~ case

• Ex)

Switch (choice) {

case 1:

case 2: printf(“파이팅!\n”); break case 3: printf(“잘했다!\n”)

case 4: printf(“멋지다!\n”); break default: printf(“잘 지내라.\n”);

}

choice = 1, 2, 3, 4, 5?

(19)

goto 조심해서 쓸 것

goto label;

..

..

..

label: statement

while (funct > 0) {

for (I = 1; I <=100; i++) {

for (j = 1; j <=50; j++) {

if(xxx)

goto help;

}

} ..

}…

help: xxx

변수이름 규칙과 동일

(20)

Today

Chapter 9. Functions ( 함수 )

• Functions and how to define them

• Arguments and return values (전달인자와 리턴값)

• Function types (함수의 데이터형)

• Declaring a function (함수 선언)

• Recursion (재귀)

• Pointers : a first look

(21)

Functions What is it?

• Functions: a self-contained unit of program code designed to accomplish a particular task.

• 함수: 하나의 특정 작업을 수행하도록 독립적으로 설계된 프로그램 코드의 한 단위

– Ex) printf(): causes data to be printed on your screen Strlen(): tells a program how long a certain string is.

• Why do we need it?

– Only one function can be used many times for repeated work.

– Imagine we write a program for printf() each time you need it. – terrible!

(22)

Functions Why use it?

• Suppose you want to write a program that does the following.

– Read in a list of numbers – Sort the numbers

– Find their average – Print a bar graph

• Functions helps you concentrate on the program’s overall design

• Using functions is more important than making them. ex) printf()

#include <stdio.h>

#define SIZE 50 Int main(void) {

Float list (SIZE);

Readlist(list, SIZE);

Sort(list, SIZE);

Average(list, SIZE);

Bargraph(list, SIZE);

Return 0;

}

(23)

Analyzing the program

Function prototype (함수 프로토타입):

tells the compiler what sort of function starbar() is

Function call (함수호출):

causes the function to be executed

Function definition (함수정의):

specifies exactly what the function does

(24)

Functions Declaration

• Any program that uses a function should declare the type before it is used – 함수의 데이터형 미리 선언.

void starbar(void);

– This line announces that the program uses a type void function called starbar() & compiler expect to find the definition for this function elsewhere. May put this inside main()

- Function type

- void indicate that there is no return value

-Default is ‘integer’

- indicates that there is no argument (전달인자)

- declaration use ; - definition don’t use ;

(25)

Functions

Calling a function

• Calls the function starbar() from main() by using its name followed by a semicolon

• Starbar();

• When finished with the code within starbar(), the computer returns to the next line of the calling function – main()

(26)

Functions Defining

• Defining starbar() is very similar to defining main()

• Uses { }, declare variables

• starbar(void) is not followed by ; - tell the compiler that you are defining.

• The variable count is a local variable. count can be used in main() without conflict.

(27)

Functions

• The program includes starbar() and main() in the same file.

• You may use two separate files.

• no return value  no communication with calling function

(28)

Function

Function argument ( 전달인자 )

(29)

Function

Function argument ( 전달인자Argument () 전달인자)

(30)

Functions

Argument ( 전달인자 )

• ch & num: argument (전달인자), formal argument

(형식전달인자) or formal parameter (형식매개변수)

• ch: char type, num: int

void show_n_char(ch, num);

char ch int num

Valid (but old style)

(31)

Functions

Arguments ( 전달인자 )

• SPACE, 8: actual argument (실전달인자)

• Formal parameter (형식매개변수): called functioin – show_n_char()

• Actual argument (실질전달인자): calling function – main()

(32)

Functions

Arguments ( 전달인자 ) & return value

• Argument send information to functions.

Calling function

ex) main() Function to be called

argument Return value

(33)

Functions

Local and global variable (지역변수와 전역변수)

(34)

Returning a value from a function with return

imin() returns min

imin()함수는 min값을 리턴함.

(35)

Functions

Local and global variable (지역변수와 전역변수)

imin(n,m);

lesser = min;

Above expressions does not work main() has no idea what min is.

(36)

Functions

return (n<m) ? n : m

If (n < m)

return n;

else return m;

same same

‘return’ terminates the function

(37)

Functions return

• Return value can be assigned to a variable, can be used as part of an expression.

– Ex) Answer = 2 * imin(z,zstar) + 25;

Printf(“%d\n”, imin(-32+answer, LIMIT));

(38)

Function

Function types

• You generally inform the compiler about functions by

declaring them in advance – should come before it is used.

• Function should be declared by type.

• A function with a return value should be declared the same type as the return value.

• If no type is given  default is ‘integer’.

(39)

Functions prototype

• One way to omit a prototype  putting entire definition before the first use

int imax(int a, int b) { return a > b? a : b;}

Int main() { …

z=imax(x,50);

… }

(40)

Recursion

• Recursion: calling itself (함수가 자기자신을 호출)

(41)

Recursion

(42)

Recursion

(43)

Recursion

(44)

Recursion

Recursion fundamentals

• Each level of function call has its own variables.

• Recursive function must contain soethingto halt the recursive calls.

(45)

Recursion

tail recursion

(46)

Compiling programs with two or more source code files

hotel.h hotel.c

- function definitions usehotel.c

- Contains main()

(47)

Compiling programs with two or more source code files

• Place the #define in a header file and use #include in each source code

• Header file contains the defined constants and function prototypes

(48)

Pointers: a first look What is it?

• Pointer: a variable whose value is a memory address

• 포인터는 주소를 값으로 가지는 변수이다.

– Char 형 변수 문자

– int형 변수 정수

포인터변수 주소

• People: a name and a value

• Computer: an address (a computer’s version of name) and a value

(49)

Pointers: a first look What is it?

p의 값은 a의 주소이고, a를 가리킨다.

(50)

Pointers: a first look What is it?

• & operator gives you the address for a variable

• pooh = 24;

• pooh: 변수의 이름, &pooh : 변수의 주소(ex. 0B76)

• Printf(“%d %p\n”,pooh,&pooh);

• 24 0B76

(51)

Pointers: a first look

the indirection operator( 간접연산자 )

ex) a = 3;

p = &a; //a를 가리키는 포인터

b = *p; //p이 가리키고 있는주소의

값을 b에 대입

b = a p = &a; 

b = *p;

p가 가리키는 주소의 값

(52)

Pointers: a first look declaring pointers

pointer a;

• Above does not provide sufficient information.

• Various types take different amount of memory and some pointer operations require knowledge of that size.

– Int *a – Char *a – Float *a

• Space between * and the pointer name is optional.

(53)

Pointers: a first look

Why do we need it? ( 왜 필요할까 ?)

How do we alter values in calling function?

– use pointer!

(54)

Pointers: a first look

Why do we need it? ( 왜 필요할까 ?)

Send ‘address’ instead of the values.

(55)

Pointers: a first look

This is why…( 이래서 필요하다 )

• X 와 y의 주소를 전달함으로써 interchange()가 그변수들에 접근할 수 있게 한다.

• 포인터와 간접연산자 *를 사용함으로써 함수는

각각의 주소에 저장되어 있는 값들을 구하고 변경할 수 있게 된다.

• 포인터는 interchange()함수의 변수들이 지역적이라는

사실을 극복해준다. Main()에 손을뻗쳐 저장되어 있는 값을 변경.

(56)
(57)

Today

Chapter 9. Functions ( 함수 )

• Functions and how to define them

• Arguments and return values (전달인자와 리턴값)

• Function types (함수의 데이터형)

• Declaring a function (함수 선언)

• Recursion (재귀)

• Pointers : a first look

(58)

Next week

Chapter 10. Arrays and Pointers (배열과 포인터)

• Arrays – initialization, assignment,

• Multidimensional arrays

• Pointers and arrays

• Functions, Arrays, and Pointers

• Pointer operations

Referensi

Dokumen terkait