การแสดงผลข้อมูล ทุกอย่างในหน่วยความจำล้วนเป็นตัวเลข การแสดงผลลัพธ์ด้วยฟังก์ชัน printf จึงต้องระบุรูปแบบตามที่เราต้องการจะเห็น char c = 65; printf("c (as a number) = %d\n", c); printf("c (as a character) = %c\n", c); หน่วยความจำ : 2 30 65 5 23 : 8 c c (as a number) = 65 c (as a character) = A ผลลัพธ์ :
17.
%format ใน scanf และ printf %s char array[] สตริง %c char อักขระโดด %lf double %f float จำนวนมีทศนิยม %llu unsigned long long %lu unsigned long %u unsigned int %lld long long %ld long %d int จำนวนเต็ม %format ชนิดตัวแปร ชนิดข้อมูล
18.
ตัวอย่างการใช้ scanfchar name[20]; int age; printf("Enter your name and age: "); scanf("%s %d", name, &age); printf("Hello %s. You are %d years old.\n", name, age); Enter your name and age: Tony 38 Hello Tony. You are 38 years old. ผลลัพธ์ :
โครงสร้าง while ลูป วนทำคำสั่ง stmt1 ถึง stmtN ตราบเท่าที่ condition เป็นจริง condition while ( condition ) { stmt1 ; stmt2 ; : stmtN ; } END START true Statement Statement false
26.
โครงสร้าง do…while ลูป ทำคำสั่ง stmt1...stmtN และวนทำซ้ำอีกตราบเท่าที่ condition ยังคงเป็นจริง นั่นคือ stmt1...stmtN จะถูกกระทำ อย่างน้อยหนึ่งครั้ง END condition do { stmt1 ; stmt2 ; : stmtN ; } while ( condition ); false START Statement 1 Statement N true
27.
ลูปวนนับ (Counting Loop) หากพิจารณาโครงสร้างของลูปที่ใช้ในโปรแกรมส่วนใหญ่ มักจะเป็นลูปแบบวนนับ ลูปวนนับจะมีส่วนประกอบดังตัวอย่างต่อไปนี้เสมอ int i, sum = 0; i = 1; while (i <= 10) { sum = sum + i; i = i + 1; } printf("Sum = %d\n", sum); ตัวแปรที่ใช้นับ ส่วนกำหนดค่าเริ่มต้น การปรับค่าตัวนับ เงื่อนไขของตัวนับ คำสั่งที่ถูกทำซ้ำ
ฟังก์ชันที่ผู้ใช้กำหนดเอง แบบไม่ส่งค่ากลับ ระบุชนิดข้อมูล void ไม่ต้องมีคำสั่ง return แบบส่งค่ากลับ ระบุชนิดข้อมูลที่ต้องการ ใช้คำสั่ง return ส่งค่าคืนตามชนิดที่ระบุ void say_hi(char *name) { printf("Hi, %s\n", name); } int max(int a, int b) { if (a > b) return a; else return b; }
34.
การไหลของโปรแกรมเมื่อใช้ฟังก์ชัน int incr(int i) { int j; j = i + 1; return j; } int main() { int k, m = 4; k = incr(m); printf ("k = %d, m = %d\n", k, m); return 0; }
ข้อผิดพลาดที่พบบ่อย #include <stdio.h> int main () { int i; scanf("%d", i); if (i = 0) puts("false"); else puts("true"); return 0; } ส่งค่า i ให้ scanf แทนที่จะส่งตำแหน่ง ใช้คำสั่งกำหนดค่า (=) แทนการเปรียบเทียบ (==)
39.
ข้อผิดพลาดที่พบบ่อย #include <stdio.h> int main () { char s[10]; printf("Enter password: "); scanf("%s", s); if (s == "pass") puts("Correct password"); else puts("Incorrect password"); return 0; } ใช้ == เปรียบเทียบสตริงไม่ได้ ใช้ฟังก์ชัน strcmp() แทน
40.
เอกสารอ้างอิง สไลด์บรรยาย การโปรแกรมภาษา C โดย รศ . ธีรวัฒน์ ประกอบผล สไลด์บรรยาย Crash Course in C โดย J . R. Cooperstock