Pointer ตัวแปรชนิดพอยเตอร์ ผู้สอน : อ.วิริยะ ไตรปัญญาศาสตร์

งานนำเสนอที่คล้ายกัน


งานนำเสนอเรื่อง: "Pointer ตัวแปรชนิดพอยเตอร์ ผู้สอน : อ.วิริยะ ไตรปัญญาศาสตร์"— ใบสำเนางานนำเสนอ:

1 Pointer ตัวแปรชนิดพอยเตอร์ ผู้สอน : อ.วิริยะ ไตรปัญญาศาสตร์

2 Pointers Variables and Memory Address
When a variable (of type int, double, char, etc.) is declared in a C program code, the operating system allocates a location for the variable somewhere in the memory. The value of the variable is stored at this location. int num = 0; 1000 num The address of the variable num 1004 1006 1008 1010

3 Variables and Memory Address
C language offers a powerful tool to access and manipulate the addresses of variables by means of pointers. The & (address of) operator Recall the use of the scanf function: scanf(“%d”, &num); The & operator, evaluates the address of the variable num. In the previous example: &num is equal to 1002.

4 Pointers Type *var_name; ตัวอย่าง int *pt;
A pointer is a variable, but unlike the other types of variables that we have seen, it contains a memory address as its value. This memory address is usually the address of another variable. To declare a pointer variable, a “*” should be put before the name : Type *var_name; ตัวอย่าง int *pt;

5 Pointer Types int *ptr_num1; (pointer to an integer or
Pointers can be declared to point to variables of any type. Examples: int *ptr_num1; (pointer to an integer or integer pointer) double *ptr_num2; (pointer to a floating point number) char *ptr_letter; (pointer to a character)

6 Pointers pointer int *ptr_num; declaration num = 0; address
int num; pointer int *ptr_num; declaration num = 0; ptr_num = # 1000 1002 1004 1006 1008 1010 num address ptr_num 1002

7 p_a a ตัวดำเนินการที่ใช้กับ Pointers The & (address of) operator
เครื่องหมาย & (Ampersand) ใช้ในการกำหนดตำแหน่งที่อยู่ของตัวแปรให้กับ pointer มีรูปแบบคือ pointer = &variable; p_a a ตัวอย่าง int a = 10; int *p_a; p_a = &a; 10 1004 1004 address 1020

8 ตัวดำเนินการที่ใช้กับ Pointers
2. The * (indirect operation) เครื่องหมาย * ใช้อ้างถึงข้อมูลหรือค่าที่เก็บไว้ในหน่วยความจำตำแหน่งที่ pointer ชี้อยู่มีรูปแบบคือ variable = *pointer;

9 int num, abc; int *ptr_num; num = 5; ptr_num = # abc = *ptr_num;
ตัวอย่าง int num, abc; int *ptr_num; num = 5; ptr_num = # abc = *ptr_num; value variable address 5 num 1000 abc 1002 1004 1006 ptr_num 1008 1010 5 1000 ptr_num “indirectly references” the value of the variable num.

10 Example Program #include <stdio.h> int main ( ){ 1002
int num1, num2, product; int *ptr_num1, *ptr_num2; num1 = 5; num2 = 7; ptr_num1 = &num1; ptr_num2 = &num2; product = num1*( *ptr_num2 ); printf(“The address of num1 is %p\n”, &num1); printf(“The value of ptr_num1 is %p\n”, ptr_num1); printf(“The value of num1 is %d\n”, num1); printf(“The value of *ptr_num1 is %d\n”, *ptr_num1); printf(“The value of product is %d\n”, product); return 0; } 5 num1 7 num2 product 35 ptr_num1 1002 ptr_num2 1004

11 Brain Exercise on Pointers
What is the output of the following code segment? #include<stdio.h> int main() { int x[5] = {0, 1, 2, 3, 4}; int *yptr, i; yptr = &x[1]; for ( i=0; i<3; i++) yptr[ i ] = -1; for (i=0; i<5; i++) printf(“%d ”, x[i]); } X[0] X[1] X[2] X[3] X[4] 1 -1 2 -1 3 -1 4 yptr[0] yptr[1] yptr[2] yptr[3]

12 1.0 2.0 3.0 -1.0 Exercise #include <stdio.h> int main() {
double x[4] = {1.0, 2.0, 3.0, 4.0}; double *xptr; int k; xptr = &x[2]; *(xptr+1) = -1.0; for (k=0; k<4; k++) printf(“%.1f ”, x[k]); } X[0] X[1] X[2] X[3] 1.0 2.0 3.0 xptr xptr + 1

13 #include <conio.h> #include <stdio.h> int main()
การเลื่อนตำแหน่งของ pointer โดยใช้เครื่องหมาย + หรือ - #include <conio.h> #include <stdio.h> int main() { int a[5]={10,15,20,25,30}; int *pa,i,n,k; pa = &a[0]; for(i=0;i<5;i++) { printf("a[%d]=%d\n",i,*pa); pa++; } getch(); return 0; } 10 15 20 25 30 a[0] a[1] a[2] a[3] a[4] a[0]=10 a[1]=15 a[2]=20 a[3]=25 a[4]=30

14 ตัวแปรพอยน์เตอร์ที่ทำหน้าที่เป็น Pointer
ตำแหน่งที่อยู่ (address) ของตัวแปร Pointer อักตัวหนึ่ง ลักษณะแบบนี้อาจเรียกว่า Indirect pointer variable pointer_ pointer_2 การกำหนดตัวแปร pointer ของ pointer มีรูปแบบดังนี้ type **pointer_var

15 int b; a = 15; p_1 = &a; p_2 = &p_1; b = **p_2;
ตัวอย่าง int a , *p_1 , **p_2; int b; a = 15; p_1 = &a; p_2 = &p_1; b = **p_2; a p_1 p_2 b address

16 จงเขียนโปรแกรมเพื่อป้อนข้อมูลเก็บในอาร์เรย์ A จำนวน n ตัว แล้วทำการเปรียบเทียบสมาชิกในอาร์เรย์ A แต่ละตำแหน่งเริ่มตั้งแต่ตำแหน่งที่ 1 จนถึง n ว่าสมาชิกในอาร์เรย์ A เรียงลำดับจากน้อยไปหามากหรือไม่ โดยส่วนของการนำข้อมูลต่างๆมาใช้ในการเปรียบเทียบ ให้ใช้ตัวแปร pointer เป็นตัวชี้ตำแหน่งข้อมูลในอาร์เรย์ A

17 #include <conio.h> #include <stdio.h> int main()
จงแสดงผลการทำงานของโปรแกรม #include <conio.h> #include <stdio.h> int main() { int a[12]={2,6,7,5,4,3,9,18,11,10,15,14}; int *pa , *pb , i , n=5; pa = &a[n]; pb = &a[0]; for(i=1 ; i<=n ; i++) { *(pa+i) += *(pb+i); *(pb+i-1) += *(pa+n-i); } printf("%d\t%d\n",*(pa+i),*(pb+i)); getch(); return 0; }

18 เซต A มีข้อมูลสมาชิกเป็น 2, 4, 5, 7, 9, 12
จงเขียนโปรแกรมเพื่อป้อนข้อมูลเก็บในเซต A และเซต B จำนวน n ตัวเท่ากัน แล้วทำการเปรียบเทียบสมาชิกในเซต A และ B ในแต่ละตำแหน่งเริ่มตั้งแต่ตำแหน่งที่ 1 จนถึง n ว่าสมาชิกในเซต A มากกว่า, เท่ากันและน้อยกว่าเซต B อยู่อย่างละกี่ตัว โดยส่วนของการนำข้อมูลต่างๆมาใช้ในการเปรียบเทียบ ให้ใช้ตัวแปร pointer เป็นตัวชี้ตำแหน่งข้อมูลของทั้งสองเซต  ตัวอย่าง เซต A มีข้อมูลสมาชิกเป็น 2, 4, 5, 7, 9, 12 เซต B มีข้อมูลสมาชิกเป็น 1, 4, 6, 9, 13, 15 ผลพิมพ์ที่ได้เป็นดังนี้ The number that set A > B = 1 The number that set A = B = 1 The number that set A < B = 4

19 Functions: Introduction
Functions are the program modules written to perform a specific task or a collection of tasks. For example, printf that we used in previous lectures is a function to display a given string on the screen.

20 Function Calls Format : FunctionName( argument list );
Arguments may be constants variables expressions Argument list consists of arguments separated by commas..

21 Function Calls - Functions may be called as a part of assignment:
Example: y = sqrt(x); - Functions may be called without an assignment: Example: printf(“Hello World”);

22 Functions: Classification
We can classify functions into two main groups: (Predefined) Library Functions: Example : printf User Defined Functions

23 (Predefined) Library Functions
Functions that are implemented as a part of C toolkit. Example: printf If a library function is used, then the corresponding header file should be included at the top of the program using preprocessor directive. Example: #include <stdio.h> for printf function

24 Some Mathematical Library Functions Defined in math.h
Function Purpose double ceil(double x) returns the smallest integer not less than x double exp(double x) returns ex double fabs(double x) returns the absolute value of x double floor(double x) returns the largest integer not greater than x double log(double x) returns the natural logarithm of x double log10(double x) returns the base 10 logarithm of x

25 Some Mathematical Library Functions Defined in math.h
Function Purpose double sin(double x) returns the sine of x (x is in radians) double cos(double x) returns the cosine of x (x is in radians) double tan(double x) returns the tangent of x (x is in radians) double sqrt(double x) returns the square root of x double pow(double x,double y) returns xy Defined in stdlib.h int abs(int x) returns the absolute value of x

26 #include <stdio.h> /* definitions of printf, scanf */
#include <math.h> /* definition of sqrt */ int main(void) { double first, second, first_sqrt, second_sqrt, sum_sqrt; /* Get first number and display its square root. */ printf("Enter the first number> "); scanf("%lf", &first); first_sqrt = sqrt(first); printf("The square root of the first number is %.2f\n", first_sqrt); /* Get second number and display its square root. */ printf("Enter the second number> "); scanf("%lf", &second); second_sqrt = sqrt(second); printf("The square root of the second number is %.2f\n", second_sqrt); /* Display the square root of the sum of the two numbers. */ sum_sqrt = sqrt(first + second); printf("The square root of the sum of the two numbers is %.2f\n", sum_sqrt); return (0); }

27 Question? What is the output of the following code? int k, l, m;
float x = 25.0, y; y = sqrt(x); k = y; l = x – k; m = sqrt(3); printf(“y=%.1f, k=%d, l=%d, m=%d”,y,k,l,m); y=5.0, k=5, l=20, m=1

28 จงเขียนโปแกรมเพื่อแก้สมการหาค่า x ที่ทำให้ค่า
f(x) = 0 เมื่อกำหนดสมการให้ดังนี้ f(x) = 3x + sin(x) – ex ให้ใช้วิธีการของนิวตันในการแก้สมการซึ่งมีสูตร ดังนี้ โดยมีเงื่อนไขในการหยุดการคำนวณเมื่อค่าสัมบูรณ์ ของ | x1 - x0 | < แต่ถ้าเงื่อนไขนี้ไม่จริงให้ แทนค่า x0 ด้วย x1 แล้วคำนวณใหม่ไปเรื่อยๆจนกว่า เงื่อนไขที่กำหนดไว้เป็นจริง จะได้ x1 เป็นคำตอบ

29 #include <conio.h>
#include <stdio.h> #include <math.h> int main() { float x0,x1,f,df; int i; printf("x0 = "); scanf("%f",&x0); printf(" x0 | x1 | f(x)\n"); for(i=0;;i++) { f = 3*x0 + sin(x0) - exp(x0); df = 3 + cos(x0) - exp(x0); x1 = x0 - f/df; if(fabs(x1-x0)< ) break; printf("%12f | %12f | %12f\n",x0,x1,f); x0 = x1; } printf("\n========================\n"); printf("The solution x1 = %f\n",x1); getch(); return 0;

30 ฟังก์ชันเกี่ยวกับสตริงก์ (String Function)
ฟังก์ชันเกี่ยวกับ string จะอยู่ในแฟ้มข้อมูล string.h จึง ต้องระบุ #include <string.h> ในตอนต้นของโปรแกรมซึ่งจะมี ฟังก์ชันต่างๆ ดังนี้ คือ strcpy (str1 , str2) ใช้ในการ copy ค่า str2 ไปยัง str1 ตัวอย่าง strcpy(str1,”Kmutt”); strcat(str1 , str2) ใช้ในการเชื่อมต่อ str1 และ str2 ผลลัพธ์จะถูกเก็บไว้ใน str1 ดัง นั้น str1 จะต้องมีขนาดใหญ่พอที่จะเก็บผลรวมของ string ทั้ง 2

31 strlen(str) ใช้หาค่าความยาวของ string strcmp(str1 , str2) ใช้ในการเปรียบเทียบ str1 และ str2 โดยใช้ค่า ASCII เป็น หลักและผลของการเปรียบเทียบจะเป็นดังนี้ ถ้า str1 < str2 จะได้ผลลัพธ์น้อยกว่าศูนย์ ถ้า str1 = str2 จะได้ผลลัพธ์เป็นศูนย์ ถ้า str1 > str2 จะได้ผลลัพธ์มากกว่าศูนย์

32 String Comparison strcmp(“thrill”, “throw”); returns a negative integer strcmp(“read”, “readable”); returns a negative integer strcmp(“shrimp”, “crab”); returns a positive integer strcmp(“end”, “end”); returns zero strncmp: Prototype: int strncmp(char *s1, char *s2, unsigned n); Purpose: Compares the first n characters of s1 and s2 returning positive, zero, and negative values as does strcmp. Example: strncmp(“read”, “readable”, 1); strncmp(“read”, “readable”, 2); strncmp(“read”, “readable”, 3); All returns zero strncmp(“read”, “readable”, 4);

33 ฟังก์ชันเกี่ยวกับตัวอักษร
ฟังก์ชันเกี่ยวกับตัวอักษรจะอยู่ในแฟ้มข้อมูล ctype.h จึง ต้องระบุ #include <ctype.h> ในตอนต้นของโปรแกรมซึ่งจะมี ฟังก์ชันต่างๆ ดังนี้ คือ tolower(ch) ใช้ในการเปลี่ยนตัวอักษรจากตัวใหญ่เป็นตัวเล็ก toupper(ch) ใช้ในการเปลี่ยนตัวอักษรจากตัวเล็กเป็นตัวใหญ่ isalnum(ch) จะให้ค่าเลขจำนวนเต็มซึ่งไม่เท่ากับศูนย์ ถ้า ch มีค่าเป็นตัวอักษรหรือตัวเลข และ จะให้ ค่าเป็นศูนย์ ถ้า ch ไม่ได้มีค่าเป็นตัวอักษรหรือ ตัวเลข

34 isalpha(ch) จะให้ค่าเลขจำนวนเต็มซึ่งไม่เท่ากับศูนย์ ถ้า ch มีค่าเป็นตัวอักษร และ จะให้ค่าเป็นศูนย์ ถ้า ch ไม่ได้มีค่าเป็นตัวอักษรรวมถึง เครื่องหมายต่างๆ isdigit(ch) จะให้ค่าเลขจำนวนเต็มซึ่งไม่เท่ากับศูนย์ ถ้า ch มีค่าเป็นตัวเลข 0 - 9 และ จะให้ค่าเป็นศูนย์ ถ้า ch ไม่ได้มีค่าเป็นตัวเลข islower(ch) ตัวเล็กและ จะให้ค่าเป็นศูนย์ ถ้า ch เป็นตัวอักษรอื่นๆ isupper(ch) ตัวใหญ่และ จะให้ค่าเป็นศูนย์ ถ้า ch เป็นตัวอักษรอื่นๆ

35 iscntrl(ch) isgraph(ch) isspace(ch) ispunct(ch)
เครื่องหมายวรรคตอน isxdigit(ch) จะให้ค่าเลขจำนวนเต็มซึ่งไม่เท่ากับศูนย์ ถ้า ch มีค่าเป็นตัวเลข ในระบบเลขฐานสิบหกได้แก่ , A-F หรือ a-f และ จะให้ค่า เป็นศูนย์ ถ้า ch เป็นตัวอักษรอื่นๆ isprint(ch) iscntrl(ch) isgraph(ch) isspace(ch)

36 abs(x) ใช้หาค่าสัมบูรณ์ของ x ซึ่งเป็นเลขจำนวนเต็ม
ฟังก์ชันอื่นๆ ทั่วไป ฟังก์ชันอื่นๆ นอกจากที่กล่าวมาแล้ว จะอยู่ในแฟ้มข้อมูล stdlib.h จึงต้องระบุ #include <stdlib.h> ในตอนต้นของ โปรแกรมซึ่งจะมีฟังก์ชันต่างๆ ดังนี้ คือ abs(x) ใช้หาค่าสัมบูรณ์ของ x ซึ่งเป็นเลขจำนวนเต็ม labs(x) ใช้หาค่าสัมบูรณ์ของ x ซึ่งเป็นเลขจำนวนเต็มยาว abort() ใช้ในการยกเลิกการทำงานของโปรแกรม ขณะนั้น และมีข้อความ Abnormal program termination ปรากฏบนจอภาพ

37 ฟังก์ชันอื่นๆ ทั่วไป(ต่อ)
atof(str) ทำหน้าที่เปลี่ยน string เป็นข้อมูลเลข ทศนิยมละเอียดสองเท่า atoi(str) ทำหน้าที่เปลี่ยน string เป็นข้อมูลเลข จำนวนเต็ม atol(str) ทำหน้าที่เปลี่ยน string เป็นข้อมูลเลข จำนวนเต็มยาว Defined in conio.h clrscr() ใช้ในการ clear จอภาพให้ว่าง clreol() ใช้ลบข้อความในบรรทัดที่ cursor อยู่ไปจน จบบรรทัดนั้น

38 Converting a String into an int using atoi
#include <stdio.h> #include <stdlib.h> int main() { char str1[ ] = "124z3yu87"; char str2[ ] = "-3.4"; char *str3 = "e24"; printf("str1: %d\n", atoi(str1)); printf("str2: %d\n", atoi(str2)); printf("str3: %d\n", atoi(str3)); return 0; } ผลการรันโปรแกรม str1: 124 str2: -3 str3: 0

39 ฟังก์ชันอื่นๆ ทั่วไป(ต่อ)
gotoxy(x , y) ใช้สำหรับการเลื่อน cursor ไปยังตำแหน่งที่ต้องการบนจอภาพ โดยที่ x เป็นตำแหน่งคอลัมน์ และ y เป็นตำแหน่งบรรทัด exit(status) ใช้ยกเลิกการทำงานของโปรแกรมขณะนั้น ค่า status ปกติจะมี ค่าเป็นศูนย์ถ้าเป็นการจบโปรแกรมตามปกติ ส่วนกรณีอื่นๆ จะ เป็นการใช้แทนข้อผิดพลาดต่างๆ delline() ใช้ลบบรรทัดที่ cursor อยู่แล้วเลื่อนบรรทัดที่อยู่ข้างล่างขึ้นมา แทนที่

40 system(“pause”); ฟังก์ชันอื่นๆ ทั่วไป(ต่อ)
insline() ใช้แทรกบรรทัดว่างลงไปใต้บรรทัดที่ cursor อยู่อีก 1 บรรทัด sizeof(x) ใช้ตรวจสอบขนาดของตัวแปรว่ามีขนาดกี่ ไบท์ system(“command”) ให้ผู้เขียนโปรแกรมสามารถ ใช้คำสั่งใน MS-DOS ได้ขณะที่ อยู่ในภาษา C ตัวอย่าง system(“dir”); system(“pause”);

41 จงเขียนโปรแกรมป้อนข้อมูลหมายเลขโทรศัพท์ แล้วแสดงผลหมายเลขโทรศัพท์เป็นคำอ่านในภาษาอังกฤษ
ตัวอย่าง ป้อนข้อมูล (Input) : แสดงผล (Output) : ZERO TWO FOUR SEVEN TWO FOUR FIVE ZERO ONE

42 User - defined Functions
Takes data (called arguments) Can take as many arguments as needed Returns data (called return type) Can only return one piece of data

43 Function Definition return_type fname(input_arguments) {
Syntax: return_type fname(input_arguments) { local variable declarations executable statements }

44 Example: Power2 function double power2(double inp) { double out;
/* Finds the square of its input argument */ double power2(double inp) { double out; out = inp*inp; return out; }

45 Functions Without Arguments & Return Value
Syntax: void fname(void) { local variable declarations executable statements }

46 Declaring and Defining a Function
For creating a user-defined function, we need: 1. Function declaration (prototype), 2. Function definition (implementation)

47 Function Declarations
Function declaration format return-value-type function-name ( arguments’ type ); Return-value-type: data type of the result (default int) void – indicates that the function returns nothing Function-name: any valid identifier Arguments’ type: comma separated list of arguments’ type

48 Function Declaration Example :
double my_function(double, double, int); float cal_function(float x, float y, int n); Each user-defined function needs to be declared All function declarations appear between The preprocessor directives, and The main function

49 #include <stdio.h> int example(double, int);
Example: Function declaration and definition in a program #include <stdio.h> int example(double, int); int main() { int b; . . . example(5.2, b) } int example(double a, int b) Function declaration (Prototype) Function definition

50 Example: Right Triangle
/* Program that calculates hypotenuse of a right triangle */ #include <stdio.h> /* because we are using printf, scanf */ #include <math.h> /* because we are using sqrt in program */ double calculate_hypotenuse(double, double); int main() { double side1, side2, hypotenuse; printf(“Please provide length of the first side :”); scanf(“%lf”, &side1); printf(“\n Please provide length of the second side:”); scanf(“%lf”, &side2); hypotenuse = calculate_hypotenuse(side1, side2); printf(“\n Hypotenuse = %f \n”, hypotenuse); return 0; } double calculate_hypotenuse(double inp1, double inp2) double out; out=sqrt(inp1*inp1+inp2*inp2); return out;

51

52 Function definition Function declaration (prototype)
#include <stdio.h> #include <conio.h> #include <math.h> float round(float x, int n); int main() { int n; float a,b; a = 1.376; b = ; a = round(a,2); b = round(b,3); printf("a = %f\n",a); printf("b = %f\n",b); getch(); } float round(float x,int n) { return floor(x*pow(10,n)+0.5)/pow(10,n); Function declaration (prototype) Function definition

53 Top - Down Design (divide and conquer)
A problem-solving method in which you first break a problem into its major subproblems. Then solve the subproblems to derive the solution to the original problem. Subproblems are typically solved by use of functions.

54 main() { function1( ____ ) function1( _____ ) { function2( ____ ) function2( _____ ) {

55 /* Draws a stick figure */
#include <stdio.h> /* function declarations (prototypes) */ void draw_circle(void); /* Draws a circle */ void draw_intersect(void); /* Draws intersecting lines */ void draw_base(void); /* Draws a base line */ void draw_triangle(void); /* Draws a triangle */ int main(void) { /* Draw a circle. */ draw_circle(); /* Draw a triangle. */ draw_triangle(); /* Draw intersecting lines. */ draw_intersect(); return (0); }

56 /* Draws a circle */ void draw_circle(void) { printf(" * \n"); printf(“ * *\n"); printf(" * * \n"); } /* Draws a base line */ void draw_base(void) printf(“ \n"); /* Draws a intersecting lines */ void draw_intersect(void) printf(" / \\ \n"); printf(“ / \\ \n"); printf(“/ \\ \n"); /* Draws a triangle */ void draw_triangle(void) draw_intersect(); draw_base();

57 ให้เขียนโปรแกรมเพื่อคำนวณหาค่า SIN(X) จากอนุกรม
โดยมีเงื่อนไขจะหยุดบวกเทอมในอนุกรมเมื่อ ค่า สัมบูรณ์ของเทอมนั้นมีค่าน้อยกว่า พร้อมทั้งหา จำนวนเทอมที่ใช้ในการหาค่าอนุกรมนี้ด้วย

58 #include <conio.h>
#include <stdio.h> #include <math.h> int fac(int x); int main() { float x,s_sin,f_sin,t=-1,s; int n=0,a; printf("input x : "); scanf("%f",&x); printf("%-10s%-10s%-10s\n","term","value","sum"); for(a=1;;a=a+2) { t = -1*t; s = t*pow(x,a)/fac(a); if(fabs(s)< )break; n++; s_sin += s; printf("%-8d%10.6f%10.6f\n",n,s,s_sin); } f_sin = sin(x);

59 printf("sin(x) from compute = %lf\n",s_sin);
printf("sin(x) from function = %lf\n",f_sin); printf("number of term = %d",n); getch(); return 0; } int fac(int x) { int f=1,i; for(i=1;i<=x;i++) f = f*i; return f;

60 ให้เขียนโปรแกรมเพื่อป้อนข้อมูลเก็บใน Array
แล้วคำนวณหาค่าที่มากที่สุดออกมา

61 #include <conio.h>
#include <stdio.h> int main() { int a[5]={8,7,3,9,2}; int b[10]={5,9,3,6,7,1,2,8,4,10}; int big,i; big = a[0]; for(i=1;i<5;i++) if(a[i]>big)big=a[i]; printf("Big a = %d\n",big); big = b[0]; for(i=1;i<10;i++) if(b[i]>big)big=b[i]; printf("Big b = %d\n",big); getch(); return 0; }

62 int big(int x[100],int n); #include <conio.h>
#include <stdio.h> int big(int x[100],int n); int main() { int a[5]={8,7,3,9,2}; int b[10]={5,9,3,6,7,1,2,8,4,10}; printf("Big a = %d\n",big(a,5)); printf("Big b = %d\n",big(b,10)); getch(); return 0; } int big(int x[100],int n) { int max,i; max = x[0]; for(i=1;i<n;i++) if(x[i] > max)max = x[i]; return max; Function declaration (prototype) Function definition

63 จงเขียนโปรแกรมเพื่อคำนวณหาค่า binomial coefficient C(n,r) หรือ nCr
จากสูตรดังนี้ โดยให้เขียนโปรแกรมการใช้ function แบบ User define function ในส่วนการคำนวณหาค่า factorial 63

64 User defined function #include <stdio.h>
#include <conio.h> double fac(int n); int main() { int n,r; double ncr; printf("Input n,r : "); scanf("%d,%d",&n,&r); ncr = fac(n)/fac(r)/fac(n-r); printf("%dC%d = %.0f",n,r,ncr); getch(); return 0; } double fac(int n) { double sum; int i; sum = 1; for(i=1;i<=n;i++) sum = sum * i; return sum; User defined function ผลการรันโปรแกรม Input n,r : 6,2 6C2 = 15

65 #include <stdio.h> int a,b,c; float x,y,z; main( ) { int m,n;
ตัวแปร Local และตัวแปร Global ตัวแปร Local เป็นตัวแปรที่กำหนดขึ้นภายใน block (เครื่องหมาย { } ) ของฟังก์ชัน ซึ่งตัแปร Local จะมีผล เฉพาะในฟังก์ชันนั้นๆ ตัวแปร Global เป็นตัวแปรที่ใช้ร่วมกันได้ทุกฟังก์ชัน ในโปรแกรมเดียวกัน โดยจะถูกเขียนไว้นอกฟังก์ชันใดๆ #include <stdio.h> int a,b,c; float x,y,z; main( ) { int m,n; float f,h; Global variables Local variables

66 Although they may have same name, they are not the same variable…
LOCAL VARIABLES Each function has its own local variables. Multiple functions (including main()) can have the local variables with the same name. Although they may have same name, they are not the same variable…

67 EXAMPLE: LOCAL VARIABLE
#include <stdio.h> void myfunc(void); int main() { int x=1; printf(“main local variable x is %d”,x); myfunc(); printf(“main local variable x is still %d”,x); return 0; } void myfunc(void) int x; x=2; printf(“ myfunc local variable x is %d”,x);

68 else return (x*fac(x-1)); }
วิธีการเขียนโปรแกรมแบบ Recursion (การเรียกซ้ำ) เป็นวิธีการเขียนฟังก์ชันขึ้นมาใช้เองและภายในฟังก์ชัน นั้นมีการเรียกใช้ฟังก์ชันนั้นซ้ำภายในตัวของมันเอง สิ่งที่จะ ต้องกำหนดขึ้นภายในฟังก์ชันเมื่อเขียนแบบ recursion คือ 1. Base cases 2. Making progress ตัวอย่าง fac(int x) { if(x == 0) return 1; else return (x*fac(x-1)); }

69 #include <stdio.h>
#include <conio.h> int f(int x); int main() { int x,s; x = 6; s = f(x); printf("The solution f(%2d) = %d\n",x,s); getch(); return 0; } int f(int x) if(x==0) return 1; else return f(x-1) + 2*x - 1;

70

71 ให้เขียนโปรแกรมเพื่อคำนวณหาค่า
ใช้วิธีแบบ recursive

72 Preprocessor directive อยู่จำนวนมาก ซึ่งจะแนะนำบางตัวให้ทราบดังนี้
เป็นการนำเอาคำสั่งอื่นๆ มารวมเข้ากับโปรแกรมที่ผู้เขียน โปรแกรมเขียนขึ้นเอง ก่อนทำการ compile โปรแกรม การเขียนคำสั่ง preprocessor จะมีเครื่องหมาย # นำหน้าและจบคำสั่งโดยไม่ต้องมีเครื่องหมาย ; ใน preprocessor จะประกอบด้วย preprocessor directive อยู่จำนวนมาก ซึ่งจะแนะนำบางตัวให้ทราบดังนี้ # define ใช้กำหนดค่าข้อมูลให้กับชื่อแมคโคร (macro_name) ที่ ตั้งขึ้น ถ้ามีการเรียกใช้ชื่อแมคโครนั้น ก็จะมีค่าตามที่กำหนด มี รูปแบบคำสั่งดังนี้ #define macro_name string

73 ชื่อแมคโคร (macro_name) อาจจะเขียนด้วยอักษรตัว
ใหญ่หรือตัวเล็กก็ได้ แต่ที่นิยนมเขียนด้วยตัวอักษรตัวใหญ่ Example: #define PI #define NEWLINE '\n' #define ABC(a,b,c) (a>b && a>c) ? 1:0

74 Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is: condition ? result1 : result2 If condition is true the expression will return result1, if it is not it will return result2. 7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5. 7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2. 5>3 ? a : b // returns the value of a, since 5 is greater than 3. a>b ? a : b // returns whichever is greater, a or b.

75 หรือ #include <file_name>
ใช้บอกให้ตัวแปลภาษา (compiler) นำแฟ้มข้อมูลอื่นมา ใช้รวมกับคำสั่งที่อยู่ภายในโปรแกรมที่เขียนขึ้นเอง มีรูปแบบคำสั่งดังนี้ #include “file_name” หรือ #include <file_name>

76 #include <conio.h>
#include <stdio.h> #include <math.h> #include <d:stat.h> int main() { int i,n; float x[100],ans; for(i=1;;i++) { printf("input x[%d] = ",i); scanf("%f",&x[i]); if(x[i]<0)break; } n = i-1; ans = sd(x,n); printf("sd = %f",ans); getch(); return 0;

77 โปรแกรมใน File : stat.h float sd(float *x,int n) {
float xbar,sum1=0,sum2=0; int i; for(i=1;i<=n;i++) { printf("x[%d] = %f\n",i,x[i]); sum1 = sum1 + x[i]; } xbar = sum1 / n; sum2 = sum2 + pow(x[i]-xbar,2); return sqrt(sum2/n); }

78 #include <conio.h>
#include <stdio.h> #include <math.h> #include <m:/C-Lab/stat.cpp> int main() { float xmean,xsd,x[100]; int i,n; for(i=1;;i++) { printf("x[%d] : ",i); scanf("%f",&x[i]); if(x[i] < 0)break; } n = i-1; xmean = mean(x,n); xsd = sd(x,xmean,n); printf("value of mean = %f\n",xmean); printf("value of sd = %f",xsd); getch(); }

79 float mean(float x[100],int n) { float sum = 0; int i;
โปรแกรมใน File : m:/C-Lab/stat.cpp float mean(float x[100],int n) { float sum = 0; int i; for(i=1;i<=n;i++) sum = sum + x[i]; return sum/n; } float sd(float x[100],float xbar,int n) float sum = 0;int i; sum = sum + pow(x[i]-xbar,2); return sqrt(sum/n);

80 ตัวอย่างโปรแกรม การส่งค่าไปยัง user-defined function และค่าข้อมูลในฟังก์ชันมีการเปลี่ยนแปลงจะมีผลกับตัวแปรในฟังก์ชัน main ด้วย เพราะการอ้างอิงเป็นแบบ address

81 #include <conio.h>
#include <stdio.h> float test(float x[100],int n); int main() { float a[100],sum=0; int i,n; for(i=1;;i++) printf("a[%d] : ",i); scanf("%f",&a[i]); if(a[i] < 0)break; } n = i-1; sum = test(a,n); for(i=1;i<=n;i++) printf("a[%d] = %8.2f\n",i,a[i]); printf("sum = %f",sum); getch(); return 0; float test(float x[100],int n) { float sum = 0; int i; for(i=1;i<=n;i++) { sum = sum + x[i]; x[i] = x[i]*i; } return sum; }

82

83

84 ให้เขียนโปรแกรมเพื่อแสดงการคำนวณหาค่าของ
กำหนดให้ใช้สูตรการคำนวณของ Trapezoidal rule คือ โดยให้ป้อนข้อมูลค่า a, b, n เข้าไปในเครื่องแล้วคำนวณหาค่า h จากสูตร

85 #include <conio.h>
#include <stdio.h> #include <math.h> int main() { int i,n; float a,b,sum,area,x,h; printf("a,b : "); scanf("%f,%f",&a,&b); printf("n : "); scanf("%d",&n); h = (b - a)/n; sum = (sqrt(a*a+2)+sqrt(b*b+2))/2; for(i=1;i<n;i++) { x = a+i*h; sum = sum + sqrt(x*x+2); } area = h*sum; printf("area = %f\n",area); getch();

86 #include <stdio.h> #include <math.h> float f(float x);
int main() { int i,n; float a,b,sum,area,x,h; printf("a,b : "); scanf("%f,%f",&a,&b); printf("n : "); scanf("%d",&n); h = (b - a)/n; sum = (f(a)+f(b))/2; for(i=1;i<n;i++) sum = sum + f(a+i*h); area = h*sum; printf("area = %f\n",area); getch(); } float f(float x) { return sqrt(x*x+2); }

87 ข้อมูลชนิดโครงสร้าง(Structure)
เป็นการรวมกลุ่มของตัวแปรเข้าด้วยกัน ภายใต้ชื่อ โครงสร้างเดียวกัน โดยมีรูปแบบดังนี้ struct structure_name { type var_name-1; type var_name-2; . type var_name-n; } sturcture_var;

88 int id; char name[40]; char address[50]; int age; } student;
ตัวอย่าง struct student_data { int id; char name[40]; char address[50]; int age; } student; การอ้างถึงตัวแปรที่อยู่ในโครงสร้าง มีรูปแบบดังนี้ structure_var.var_name เช่น student.name

89 การกำหนดตัวแปรให้มีโครงสร้างเหมือนกับกลุ่ม
โครงสร้างที่มีอยู่แล้ว มีรูปแบบดังนี้ struct structure_name structure_var; เช่น struct student_data chem,math;

90 ข้อมูลแบบยูเนียน(union)
เป็นข้อมูลชนิดหนึ่งคล้ายกับข้อมูลแบบโครงสร้าง โดย สมาชิกทุกตัวจะใช้หน่วยความจำเดียวกัน โดยมีรูปแบบดังนี้ union union_name { type var_name-1; type var_name-2; . type var_name-n; } union_var;

91 int a; char b; } var_ab; การกำหนดค่าหรืออ้างถึงข้อมูลใน union a b
ตัวอย่าง union data_ab { int a; char b; } var_ab; การกำหนดค่าหรืออ้างถึงข้อมูลใน union var_ab.a = 25; a b

92 fp = fopen(f_name,mode);
การเปิดแฟ้มข้อมูล (File) การเปิดแฟ้มข้อมูลมีรูปแบบดังนี้ FILE *fp fp = fopen(f_name,mode); fp เป็น file pointer ของข้อมูลแบบโครงสร้างชนิด FILE fopen เป็นฟังก์ชันที่ใช้ในการเปิดแฟ้มข้อมูล f_name เป็นชื่อแฟ้มข้อมูล mode เป็น status ของการเปิดแฟ้มข้อมูล “r” เปิดไฟล์เพื่อการอ่านข้อมูล “w” สร้างไฟล์ใหม่เพื่อบันทึกข้อมูล “a” เปิดไฟล์เพื่อเพิ่มข้อมูลต่อท้ายไฟล์

93 fclose(fp); fscanf(fp,control_string,var_list);
รูปแบบข้อมูลกำหนดได้ 2 แบบ t บันทึกข้อมูลแบบข้อความ Text b บันทึกข้อมูลแบบเลขฐานสอง Binary การปิดแฟ้มข้อมูล fclose(fp); ฟังก์ชัน fprintf() และ fscanf() เป็นการเขียนและอ่านข้อมูลกับไฟล์ มีรูปแบบดงนี้ fprintf(fp,control_string,var_list); fscanf(fp,control_string,var_list);

94 #include <stdio.h>
#include <conio.h> main() { int i; FILE *mathfile; mathfile = fopen(“a:test.txt”,”wt”); clrscr() for(i=1;i<=20;i++) fprintf(mathfile,”%d\n”,i); fclose(mathfile); }

95 #include <stdio.h>
#include <conio.h> main() { int i,a; FILE *mathfile; mathfile = fopen(“a:test.txt”,”rt”); clrscr() for(i=1;i<=5;i++) fscanf(mathfile,”%d”,&a); printf(“a[%d] = %d\n”,i,a); } fclose(mathfile);

96 การลบ (Delete)ข้อมูลออกจากแฟ้มข้อมูล

97 #include <conio.h>
#include <stdio.h> int main() { int i,del,a; FILE *fp; FILE *fp2; fp = fopen("test.dat","rt"); fp2 = fopen("uptest2.dat","wt"); printf("delete # : "); scanf("%d",&del); for(i=1;i<=20;i++) { fscanf(fp,"%d",&a); if(feof(fp)!=0)break; if(del==a)continue; fprintf(fp2,"%d\n",a); } fclose(fp); fclose(fp2); getch(); }

98 #include <conio.h>
#include <stdio.h> int main() { int i,a,n; FILE *stfile; stfile = fopen("m:/c-lab/test.dat","r"); FILE *upfile; upfile = fopen("m:/c-lab/uptest.dat","w"); printf("input insert data no. : "); scanf("%d",&n); for(i=1;;i++) fscanf(stfile,"%d",&a); if(feof(stfile)!=0)break; if(a<n) fprintf(upfile,"%d\n",a); else { fprintf(upfile,"%d\n",n); break;} }

99 for(i=1;;i++) { fprintf(upfile,"%d\n",a); fscanf(stfile,"%d",&a); if(feof(stfile)!=0)break; } fclose(stfile); fclose(upfile); getch();

100 #include <conio.h>
#include <stdio.h> void main() { int i,j,id,price; char name[20],author[20]; FILE *stfile; stfile = fopen("book.dat","wt"); for(i=1;;i++) { clrscr(); gotoxy(20,5);printf("record no # %d",i); gotoxy(20,6);printf("book id :"); gotoxy(20,7);printf("book name :"); gotoxy(20,8);printf("author :"); gotoxy(20,9);printf("price :"); gotoxy(32,6);scanf("%d",&id); if(id==0)break;

101 gotoxy(32,7);scanf("%s",&name);
gotoxy(32,8);scanf("%s",&author); gotoxy(32,9);scanf("%d",&price); fprintf(stfile,"%d %s %s %d\n",id,name,author,price); } fclose(stfile);

102 #include <conio.h>
#include <stdio.h> void main() { int i,j,id,price; char name[20],author[20]; FILE *stfile; stfile = fopen("book.dat","rt"); clrscr(); printf("No. Book_id NAME "); printf("AUTHOR PRICE\n"); for(i=1;;i++) fscanf(stfile,"%d%s%s%d",&id,&name,&author,&price); if(feof(stfile)!=0)break; printf("%-5d%-10d%-20s%-20s%d\n",i,id,name,author,price); } fclose(stfile);

103 #include <stdio.h> main( ) { FILE *fp;
ในการใช้ฟังก์ชัน fopen( ) จะให้ค่า NULL ถ้าไม่สามารถเปิด File ได้ ตัวอย่าง #include <stdio.h> main( ) { FILE *fp; If((fp=fopen(“math.dat”,”w”))==NULL) printf(“cannot open file\n”); return 0; }

104 fgets(str , num , fp); ฟังก์ชัน fputs() และ fgets()
เป็นการเขียนและอ่านข้อมูล string กับไฟล์ มีรูปแบบดังนี้ fputs(str , fp); fgets(str , num , fp);

105 #include <conio.h>
#include <stdio.h> #include <string.h> void main() { int i,j; char name[20],author[20],sp[1],id[5],price[7]; FILE *stfile; stfile = fopen("book4.dat","wt"); for(i=1;;i++) { clrscr(); gotoxy(20,5);printf("record no # %d",i); gotoxy(20,6);printf("book id :"); gotoxy(20,7);printf("book name :"); gotoxy(20,8);printf("author :"); gotoxy(20,9);printf("price :"); gotoxy(32,6);gets(id); if(id[0]=='\0')break;

106 gotoxy(32,7);gets(name);
gotoxy(32,8);gets(author); gotoxy(32,9);gets(price); strcat(id,"\n"); fputs(id,stfile); strcat(name,"\n"); fputs(name,stfile); strcat(author,"\n"); fputs(author,stfile); strcat(price,"\n"); fputs(price,stfile); } fclose(stfile);

107 #include <conio.h>
#include <stdio.h> #include <stdlib.h> void del(char a[20]); void main() { int i,j,i_id,i_price; char name[20],author[20],id[5],price[7]; FILE *bfile; bfile = fopen("book4.dat","rt"); FILE *bfile2; bfile2 = fopen("report.dat","wt"); clrscr(); fprintf(bfile2,"No. Book_id NAME "); fprintf(bfile2,"AUTHOR PRICE\n"); for(i=1;;i++) fgets(id,5,bfile); fgets(name,20,bfile);

108 fgets(author,20,bfile); fgets(price,7,bfile); if(feof(bfile)!=0)break; i_id = atoi(id); i_price = atoi(price); del(name); del(author); fprintf(bfile2,"%-4d%-9d%-20s",i,i_id,name); fprintf(bfile2,"%-20s%d\n",author,i_price); } fclose(bfile); fclose(bfile2); void del(char a[20]) { int i; for(i=0;i<20;i++) if(a[i]=='\n')break; a[i] = '\0';

109 pt เป็น pointer ของตัวแปร bytes เป็นขนาดของตัวแปร n เป็นจำนวนข้อมูล
ฟังก์ชัน fwrite() และ fread() ในการสร้าง file แบบ record เป็นการเขียนและอ่านข้อมูลกับไฟล์ มีรูปแบบดังนี้ fwrite(pt , bytes , n , fp); fread(pt , bytes , n , fp); pt เป็น pointer ของตัวแปร bytes เป็นขนาดของตัวแปร n เป็นจำนวนข้อมูล fp เป็น file pointer

110 #include <conio.h>
#include <stdio.h> #include <string.h> struct data { int id; char name[20]; char author[20]; int price; }book; void main() { int i,j; char sp[1]; FILE *stfile; stfile = fopen("book3.dat","wb"); for(i=1;;i++) { clrscr(); gotoxy(20,5);printf("record no # %d",i); gotoxy(20,6);printf("book id :"); gotoxy(20,7);printf("book name :"); gotoxy(20,8);printf("author :");

111 gotoxy(20,9);printf("price :");
gotoxy(32,6);scanf("%d",&book.id); if(book.id==0)break; gets(sp); gotoxy(32,7);gets(book.name); gotoxy(32,8);gets(book.author); gotoxy(32,9);scanf("%d",&book.price); fwrite(&book,sizeof book,1,stfile); } fclose(stfile);

112 #include <conio.h>
#include <stdio.h> struct data { int id; char name[20]; char author[20]; int price; }book; void main() { int i,j; FILE *stfile; stfile = fopen("book3.dat","rb"); clrscr(); printf("No. Book_id NAME "); printf("AUTHOR PRICE\n");

113 printf("%-4d%-9d%-20s",i,book.id,book.name);
for(i=1;;i++) { fread(&book,sizeof book,1,stfile); if(feof(stfile)!=0)break; printf("%-4d%-9d%-20s",i,book.id,book.name); printf("%-20s %d\n",book.author,book.price); } fclose(stfile);

114 #include <stdio.h>
#include <conio.h> int f(int a); int x,s; int main() { x=6; s = f(x); printf("The solution f(%2d) = %d\n",x,s); getch(); } int f(int a) if(a==0) return 0; else return f(a-1) + 2*a - 1;

115

116 จงเขียนโปรแกรมเพื่อป้อนตัวเลข 1-9 แล้วให้แสดงผลดังรูปที่กำหนดให้

117 #include <conio.h>
#include <stdio.h> int main() { int i,j,k,n; printf("input the number : "); scanf("%d",&n); for(i=1;i<=2*n+3;i++) printf("*"); printf("\n"); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) printf(" "); for(k=1;k<=n-i+1;k++) printf("%d",k); for(k=n-i;k>=1;k--) } for(i=1;i<=n+1;i++) printf(" "); printf("*\n"); getch(); return 0; }

118 จงเขียนโปรแกรมเพื่อป้อนข้อมูล Matrix ขนาด n x n และให้เขียนฟังก์ชันในแบบ User define function เพื่อให้สามารถแลกเปลี่ยนข้อมูลระหว่างแถวนอน(Row) จากแถวนอนหนึ่งไปยังอีกแถวนอนหนึ่ง

119 #include <conio.h>
#include <stdio.h> swap(int a[10][10],int n,int r1,int r2); void main() { int a[10][10],i,j,n,r1,r2; clrscr(); printf("input order of matrix n = "); scanf("%d",&n); printf("input matrix A\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { printf("a[%d][%d] = ",i,j); scanf("%d",&a[i][j]); }

120 printf("\ninput row number for swapping (r1,r2) : ");
scanf("%d,%d",&r1,&r2); swap(a,n,r1,r2); printf("Output matrix A\n"); for(i=1;i<=n;i++) {printf("\n"); for(j=1;j<=n;j++) printf("%5d",a[i][j]); } swap(int a[10][10],int n,int r1,int r2) { int i,j,temp; { temp = a[r1][i]; a[r1][i] = a[r2][i]; a[r2][i] = temp; }

121 จงเขียนโปรแกรมป้อนข้อมูลประโยคภาษาอังกฤษ แล้วหาว่ามีคำว่า The หรือ the
อยู่กี่คำ

122 #include <stdio.h>
#include <conio.h> int main() { char word[40]; int i,n=0; printf("input sentence : "); gets(word); for(i=0;word[i]!='\0';i++) { if(word[i]=='T' || word[i]=='t') if(word[i+1]=='h') if(word[i+2]=='e') n = n+1; } printf("Number of word 'The' = %d",n); getch(); return 0;

123 จงเขียนโปรแกรมป้อนข้อมูลคำในภาษาอังกฤษ แล้วเรียงลำดับตัวอักษรในคำนั้นใหม่จากน้อยไปหามาก (ตามค่า ASCII Code) และแสดงผลออกมาด้วย

124 #include <conio.h>
#include <stdio.h> #include <string.h> #include <ctype.h> int main() { char word[20],buff; int i,j,k,n; printf("Input word : "); gets(word); n = strlen(word); for(i=0;i<n-1;i++) for(j=i+1;j<n;j++) { if(toupper(word[i])< toupper(word[j])) continue; else { buff = word[i]; word[i] = word[j]; word[j] = buff; } } printf("Output : %s",word); getch(); return 0; }

125


ดาวน์โหลด ppt Pointer ตัวแปรชนิดพอยเตอร์ ผู้สอน : อ.วิริยะ ไตรปัญญาศาสตร์

งานนำเสนอที่คล้ายกัน


Ads by Google