Fundamentals of Computer System - chapter 9. Functions 민기복 Ki-Bok Min, PhD 서울대학교에너지자원공학과조교수 Assistant Professor, Energy Resources Engineering
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()
if statement three general forms if (expression) statement if (expression) statement1 else (expression2) statement2 if (expression1) statement1 else if (expression2) statement2 else statement3
if statement general form (1) if (expression) statement a single statement or a single block with { } if value > 0 Branching statement ( 분기문 ) Test/execution is done only once while??? false true printf ( 양수입니다 n )
if statement general form (2) if (expression) statement1 else (expression) statement2 else if value > 0 true printf ( 음수입니다.\n ) printf ( 양수입니다 n )
if statement general form (3) if (expression1) statement1 else if (expression2) statement2 else if if value > 0 else statement3 else value < 0 true true printf ( 0 입니다.\n ) printf ( 음수입니다.\n ) printf ( 양수입니다 n )
if statement general form (3)
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
if statement pairing else with if if (number > 6) if (number <12) else When number is 5??? printf( You are close!\n ); printf( Sorry, you lose a turn!\n ); Very important to have proper indentations ( 띄어쓰기 )!
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);
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
Logical operator order of evaluation and range if (range >= 90 && range <= 100 ) printf( A\n ); if (90<= range <= 100 ) printf( A\n ); Don t do this! Semantic error! (90<= range) <= 100 always true 0 or 1
Conditional operator ( 조건연산자 )?:?: the only tertiary operator ( 삼항연산자 ) x = (y < 0)? y : y; If (y<0) x = -y; else x = y; General form Expression1? Expression2 : Expression 3 true ex) max = (a > b)? a : b; false
Loop Aids: Continue and break 처리의순서나흐름을조절하는제어문 continue: 해당루프의나머지를건너뛰고, 해당루프의다음사이클을시작. break: 어떤처리의순서나흐름을중단하고, 루프를탈출. 중첩구조에서는내부구조만영향을받음.
Continue and break while (( ch = getchar() )! EOF) { blabla(ch); if (ch == \n ) continue yakyak(ch); } blunder(n,m); while (( ch = getchar() )! EOF) { blabla(ch); if (ch == \n ) break; yakyak(ch); } blunder(n,m);
Multiple choices: switch ~ case switch (integer expression) { case constant1: statement1; expression & case label : integer (including char) No case label matches expression: default case constant2: statement2; } default: statements;
Multiple choices: switch ~ case Switch~case with break Switch~case without break
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?
goto 조심해서쓸것 goto label;...... 변수이름규칙과동일 label: statement while (funct > 0) {.. } for (I = 1; I <=100; i++) { } help: xxx for (j = 1; j <=50; j++) { if(xxx) } goto help;
Today Chapter 9. Functions ( 함수 ) Functions and how to define them Arguments and return values ( 전달인자와리턴값 ) Function types ( 함수의데이터형 ) Declaring a function ( 함수선언 ) Recursion ( 재귀 ) Pointers : a first look
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!
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; }
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
Functions Declaration Any program that uses a function should declare the type before it is used 함수의데이터형미리선언. void starbar(void); - Function type - void indicate that there is no return value -Default is integer - declaration use ; - definition don t use ; - indicates that there is no argument ( 전달인자 ) 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()
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()
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.
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
Function Function argument ( 전달인자 )
Function Function argument ( 전달인자 ) Argument ( 전달인자 )
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)
Functions Arguments ( 전달인자 ) SPACE, 8: actual argument ( 실전달인자 ) Formal parameter ( 형식매개변수 ): called functioin show_n_char() Actual argument ( 실질전달인자 ): calling function main()
Functions Arguments ( 전달인자 ) & return value Argument send information to functions. Calling function ex) main() argument Return value Function to be called
Functions Local and global variable ( 지역변수와전역변수 )
Returning a value from a function with return imin() returns min imin() 함수는 min 값을리턴함.
Functions Local and global variable ( 지역변수와전역변수 ) imin(n,m); lesser = min; Above expressions does not work main() has no idea what min is.
Functions return (n<m)? n : m same same return terminates the function If (n < m) return n; else return m;
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));
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.
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); }
Recursion Recursion: calling itself ( 함수가자기자신을호출 )
Recursion
Recursion
Recursion
Recursion Recursion fundamentals Each level of function call has its own variables. Recursive function must contain soethingto halt the recursive calls.
Recursion tail recursion
Compiling programs with two or more source code files usehotel.c - Contains main() hotel.c - function definitions hotel.h
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
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
Pointers: a first look What is it? p 의값은 a 의주소이고, a 를가리킨다.
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
Pointers: a first look the indirection operator( 간접연산자 ) p = &a; b = *p; p 가가리키는주소의값 b = a ex) a = 3; p = &a; b = *p; //a 를가리키는포인터 //p 이가리키고있는주소의값을 b 에대입
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.
Pointers: a first look Why do we need it? ( 왜필요할까?) How do we alter values in calling function? use pointer!
Pointers: a first look Why do we need it? ( 왜필요할까?) Send address instead of the values.
Pointers: a first look This is why ( 이래서필요하다 ) X 와 y 의주소를전달함으로써 interchange() 가그변수들에접근할수있게한다. 포인터와간접연산자 * 를사용함으로써함수는각각의주소에저장되어있는값들을구하고변경할수있게된다. 포인터는 interchange() 함수의변수들이지역적이라는사실을극복해준다. Main() 에손을뻗쳐저장되어있는값을변경.
Today Chapter 9. Functions ( 함수 ) Functions and how to define them Arguments and return values ( 전달인자와리턴값 ) Function types ( 함수의데이터형 ) Declaring a function ( 함수선언 ) Recursion ( 재귀 ) Pointers : a first look
Next week Chapter 10. Arrays and Pointers ( 배열과포인터 ) Arrays initialization, assignment, Multidimensional arrays Pointers and arrays Functions, Arrays, and Pointers Pointer operations