Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Executable Statements ในภาษา C

ความหมาย

Executable statements คือคำสั่งที่คอมไพเลอร์แปลงเป็น machine code และ CPU ทำงานจริงเมื่อโปรแกรมรัน

ประเภทของ Executable Statements

  1. Input-Output Statements
  2. Assignment Statements

1. Input-Output Statements

Input Operation

เก็บค่าจาก input device (keyboard) ลงหน่วยความจำ

Output Operation

แสดงผลลัพธ์จากหน่วยความจำไปยัง output device (หน้าจอ)

Common I/O Functions (stdio.h)

  • printf() - formatted output
  • scanf() - formatted input
  • getchar()/putchar() - character I/O
  • gets()/puts() - string I/O (gets deprecated)
  • fgets()/fputs() - file/string I/O (ปลอดภัยกว่า)

printf() Syntax

printf("format string", print_list);

ตัวอย่าง: printf("ค่าเฉลี่ย = %f", avg);

scanf() Syntax

scanf("format string", input_list);

ตัวอย่าง: scanf("%d %f", &a, &b);

  • Input list ต้องนำหน้าด้วย & (address-of operator)
  • คืนค่าจำนวน items ที่อ่านสำเร็จ

2. Assignment Statements

เก็บค่าในตัวแปร และทำ arithmetic operations

Syntax

variable = expression;

ตัวอย่าง

  • c = a + b;
  • avg = sum / 3;
  • r1 = (b * b - 4 * a * c);

ตัวอย่างโปรแกรม: คำนวณค่าเฉลี่ย 3 ตัวเลข

#include <stdio.h>
int main() {
    int a, b, c, sum;
    float avg;
    printf("ป้อนค่า a, b, c: ");
    scanf("%d%d%d", &a, &b, &c); // Input statement
    sum = a + b + c;             // Assignment statement
    avg = sum / 3.0;             // Assignment statement (3.0 เพื่อ float division)
    printf("ค่าเฉลี่ย avg = %f\\n", avg); // Output statement
    return 0;
}

ผลลัพธ์

ป้อนค่า a, b, c: 2 3 4
ค่าเฉลี่ย avg = 3.000000

Statement ต่อ Statement

C ใช้ semicolon (;) จบ statement ทุกคำสั่ง

a = 10;           // Assignment statement
printf("%d", a);   // Expression statement (function call)
if (a > 0) b = 1;  // If statement (compound statement)

Compound Statement (Block)

กลุ่ม statements ใน { } ใช้ได้ทุกที่ที่ statement เดียวใช้ได้

คำสั่งควบคุม (Control Statements) - ยังเป็น Executable

  • Selection: if, if-else, switch
  • Iteration: while, for, do-while
  • Jump: break, continue, goto, return

Non-Executable Statements

ไม่สร้าง machine code: #include, #define, typedef, variable declarations (without initialization), function prototypes