1 / 22

Computer Programming in C Chapter 4

Computer Programming in C Chapter 4. 2004 년 가을학기 부산대학교 전자전기정보컴퓨터공학부. 4 장 . 함수와 프로그램 구조. 목차 Function Function 의 Parameter Passing 과 Return Value Scope Rule Variable 의 종류에 따른 저장장소 Static Variable Recursion Macro and Preprocessor. 1. Function : Example. 1. Function : 기본 개념.

Download Presentation

Computer Programming in C Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Computer Programming in C Chapter 4 2004년 가을학기 부산대학교 전자전기정보컴퓨터공학부

  2. 4장. 함수와 프로그램 구조 • 목차 • Function • Function의 Parameter Passing과 Return Value • Scope Rule • Variable의 종류에 따른 저장장소 • Static Variable • Recursion • Macro and Preprocessor Computer Programming Chapter 2

  3. 1. Function : Example Computer Programming Chapter 2

  4. 1. Function : 기본 개념 • 동일한 프로그램의 반복을 조직화. • 프로그램의 전체적인 구조를 체계적으로. • 반복적인 프로그램의 재사용 • 예. printf, scanf 등이 모두 함수로 구현 • Function의 수행과정 A A 함수의 호출 X1 X Function 반복적 수행 B B X2 C C Computer Programming Chapter 2

  5. 1. Function : Syntax • Function의 기본적 Syntax • Caller : Function 을 호출하는 부분 return_value = function_name (parameter1, parameter2, ... ); • Callee : Function 자체 (호출되어 실행되는 부분) typefunction_name (parameter1, parameter2, ... ) type parameter1; type parameter2; . . . { /* function body */ } • Function Body에는 반드시 return statement를 포함 Computer Programming Chapter 2

  6. 1. Function : Example . . . chemAvg=average(chem, 120); phyAvg=average(phy, 150); } float average(score, num) int score[],num; { int i=0; float sum; sum=0.0; while(i<num) sum+=score[i++]; return sum/num; } Actual Parameters : 실제 값을 넘겨주는 Parameter 함수의 호출 Formal Parameters : 값을 넘겨 받기위한 변수 Return Type : return되는 값을 type Function Body Computer Programming Chapter 2

  7. 2. Function의 Parameter Passing • Parameter Passing • 함수를 호출할 때, Formal Parameter에 값을 지정하는 과정 • Call by value에 의한 방식으로 전달 • 같은 Type으로 전달 • Array를 Parameter로 전달할 경우 int mathScore[100]; MathAverage=Average(100, mathScore ); float Average(N,score) int N, score[]; Array의 전달 Computer Programming Chapter 2

  8. 2. Function의 Return Value • Function의 수행결과를 받는 방법 • Function의 Return Value • Parameter : Pointer를 이용(나중에 설명) • Global(External) Variable의 결과 • Return Value • "return" statement을 이용 • Function 자체의 결과로 전달 • return value의 type을 지정하여야 함 Computer Programming Chapter 2

  9. 3. Scope Rule • Variable이 유효한 범위를 지정하는 법칙 • Block의 단위로 유효 float average(score, num) int score[],num; { int x; x=10; while(i<num) { int x; x=20; } } 해당 Block에서만 유효 Computer Programming Chapter 2

  10. 3. Scope Rule • 각 종류별로 적용되는 Scope • Parameter : 해당 함수 Block 내에서 유효 • Local Variable : 선언된 Block 내에서 유효 • 예외 : Global Variable • 함수 밖에서 선언된 Variable : 함수명 앞에 선언 • File 내에서는 모두 유효 • 다른 File에서 변수를 공유하려면 : "external" 선언 • 모든 함수명은 일종의 Global Variable • 교재 p.76-77의 Stack 에 대한 프로그램 참조 Computer Programming Chapter 2

  11. 4. Programming Assignment #6 • Programming Assignment #3와 같이 입력된 데이터 파일에서 각 학과별 평균성적을 출력 하시오. 단. 각 학과별 학생의 수는 100명을 넘지 않으며, 다음의 함수를 반드시 이용하여 프로그램하여야 한다. float Average(score, n) int score[]; int n; Computer Programming Chapter 2

  12. 5. Variable의 종류별 저장장소 • Variable의 종류에 따라 저장되는 장소 • 모든 Variable에는 주기억 장치의 저장공간이 할당됨 • Global Variable • 정적인 기억공간 : 프로그램의 수행과 관계없이 일정한 공간을 할당받음 • Local Variable 과 Function의 Parameter • Stack 이라는 방식의 기억공간에 동적인 기억공간 • Stack : Last-In First-Out 방식의 동적인 기억공간 Computer Programming Chapter 2

  13. 5. Variable의 종류별 저장장소 : Stack Out In Stack으로 할당된 공간 8 Stack Top(=8) 4 0 Stack Bottom(=0) 주기억장치의 공간 Stack 에 입력되는 데이터의 크기에 따라 Stack Top(SP:Stack Point)의 값이 변경 (In : SP+=SP, Out: SP-=4) Computer Programming Chapter 2

  14. Return address(average) Parameter : score Parameters : num Local Variable : i Local Variable : x Local Variable : x 5. Variable의 종류별 저장장소 : Local Variable의 저장장소 float average(score,num) int score[],num; { int i,x; x=10; while(i<num) { int x; x=20; } } 이미 사용중 Computer Programming Chapter 2

  15. 6. Programming Assignment #7 • 두개의 삼각형이 겹치는 넓이를 구하는 함수를 프로그램하시오. 단 삼각형의 세점이 일직선상에 있는 경우는 겹치는 넓이를 0으로 하시오. float intersectiongArea(triangle1, triangle2) float triangle1[]; /* x1=triangle[0],y1=triangle[1],x2=triangle[2], */ float triangle2[]; /* y2=triangle[3],x3=triangle[4],y3=triangle[5] */ • 위의 함수를 이용하여, 주어진 N 개의 삼각형중 가장 겹치는 넓이가 많은 삼각형쌍의 번호와 넓이를 출력하시오. 삼각형의 데이터는 triang.dat에 다음과 같이 주어집니다. N (삼각형의 수) x11, y11, x12, y12, x13, y13 . . . xN1, yN1, xN2, yN2, xN3, yN3 Computer Programming Chapter 2

  16. 7. Static Variable • 주어진 Block 내에서만 유효한 변수 • 그러나, Block을 벗어나도 변수의 값이 남아 있는 특성 • Local Variable과 달리 Stack에 저장되지 않음 예. float functionAny() { static int count=0; . . . count++; } Computer Programming Chapter 2

  17. 8. Recursion • 옛날에 어느 외로운 할아바지와 할머니가 살았습니다. 어느 날, 젊은 나그네가 와서 하루 밤만 재워달라고 하였습니다. 그래서 할아버지가 말씀하셨습니다. "여보게 젊은이, 우리 집에서 하루 밤을 자려면, 우리에게 재미있는 이야기를 해야 하네." 그 말을 들은 젊은 이는 그렇게 하겠다고 하고 집에 들어가 할머니가 차려 주시는 저녁을 맛있게 먹었습니다. 그리고, 젊은 이는 할아버지와 할머니에게 재미있는 이야기를 들려주기 시작하였습니다. "옛날에 어느 외로운 할아바지와 할머니가 살았습니다. 어느 날, 젊은 나그네가 와서 하루 밤만 재워달라고 하였습니다. 그래서 할아버지가 말씀하셨습니다. "여보게 젊은이, 우리 집에서 하루 밤을 자려면, 우리에게 재미있는 이야기를 해야 하네." 그 말을 들은 젊은 이는 그렇게 하겠다고 하고 집에 들어가 할머니가 차려 주시는 저녁을 맛있게 먹었습니다. 그리고, 젊은 이는 할아버지와 할머니에게 재미있는 이야기를 들려주기 시작하였습니다. " ... 이하 생략 • FunnyStory( ) { AGrandFatherAndGrandMother(); AVisitOfAYoungMan(); FunnyStory(); } 어떤 일이 일어날까 ? Computer Programming Chapter 2

  18. 8. Recursion • Recursion : • Function이 다시 자신을 호출하는 경우 • 반드시 Termination Condition이 있어야 함 • 사용 방식 type functionName(parameters) { if(TerminalCodition) return value; else { . . . functionName(parameters'); } } Recursion을 종료하는 조건 Recursive Call Parameter의 값이 변경되어야 함 Computer Programming Chapter 2

  19. 8. Recursion : Sample 예제 1 int RecursiveSum(int values[], int n) { if(n==0) return 0; else return values[n-1] + RecursiveSum(values, n-1); } 예제 2 /* suppose that values are sorted by ascending order */ int binarySearch(int values[],int low,int high,int key) { int m; if(high<=low) then return -1; /* it means NOT FOUND */ m = (high+low)/2; if(values[m]==key) return m; else if(key < values[m]) return binarySearch(values,low,m-1,key); else return binarySearch(values,m+1,high,key); } Computer Programming Chapter 2

  20. 9. Macro and Preprocessor • '#'으로 시작하는 문장 • 실행되는 문장이 아님 • Compiler 에게 전처리를 요구하는 명령 • #include : 지정된 File을 지정된 위치에 삽입 • #if condition program #endif condition이 만족되면 program을 삽입, 아니면 삭제 • #define : Macro의 정의 Computer Programming Chapter 2

  21. 9. Macro and Preprocessor • #define으로 시작 문장 • 단순한 substitution(대치) : Function과 구별 • Syntax #define macroNameexpression * 여러 줄일 경우는 back slash(\)로 다음 줄과 연결 • 예 #define BUFSIZ 512 #define max(a,b) ((a)>=(b)?(a):(b)) . . . k=max(x+2,y*y); /* k=((x+2)>=(y*y)?(x+2):(y*y))와 동일 Computer Programming Chapter 2

  22. 10. Programming Assignment #8 • 실수 Array인 Values의 평균을 구하는 다음과 닽은 Macro를 작성하시오. #define Average(values,n,mean) . . . * 단 values는 n개의 값을 가지는 array로 미리 선언되어 있고, n은 실수 값의 개수이며, mean은 계산된 결과의 평균이다. • 위의 Macro를 이용하여 Programming Assignment에서 주어지는 data의 평균을 구하는 프로그램을 완성하시오. Computer Programming Chapter 2

More Related