此篇文章是紀錄C的控制結構虛擬碼撰寫注意事項:

C共有三種控制結構(Control structure), 三大類加總共有7個控制敘述式 :
三大類:
1. 循序結構(Sequential structure)
2. 選擇結構(Selection structure)
    1)if (single-selection statement)
    2)if, else (double-selection statement)
    3)switch (multiple-selection statement)
3. 重複結構(Repetition structure)
    1)while
    2)do, while
    3)for

虛擬碼(pseudo code)則是 :
1. 讓讀者能思考程式該如何撰寫
2. 完全由字元組成(因為虛擬碼可以用不同程式語言實作)
3. 能夠將虛擬碼的敘述式換成相等的c敘述式
4. 只包含動作敘述式

以下介紹虛擬碼的寫法 :
[總敘述式(Top)虛擬碼] :
總敘述式是一個單一敘述式,它涵蓋了程式所有的功能。
舉例來說 : 如果有一支程式用來計算班上所有同學某科的平均成績。
那麼敘述式虛擬碼則寫成  :
Determine the class average for the quiz.

接下來介紹選擇結構中的兩個控制敘述式與重複結構中的一個while控制敘述式虛擬碼的寫法 :
1. if 選擇敘述式(selection statement) :
如果程式碼如下所示 :

[code]
if(grade>=60)printf("Passed");
[/code]

那麼虛擬碼就要寫成 :
[pseudo_code]
If student's grade is greater than or equal to 60
   Print "Passed"
[/pseudo_code]

2. if-else選擇敘述式 :
[code]
if(grade>=60)
{
   printf ("Passed");
}else
{
   printf("Failed");
}
[/code]

虛擬碼 :
[pseudo_code]
If student's grade is greater than or equal to 60
   Print "Passed"
else
   Print "Failed"
[/pseudo_code]

3. 巢狀if else敘述式(Nested if...else statement) :
[code]
if(grade>=90)
   printf("A");
else
   if(grade>=80)
      printf("B");
   else
      if(grade>=70)
         printf("C");
      else
         printf ("F");
[/code]

虛擬碼則為 :
[pseudo_code]
If student's grade is greater or equal to 90
   Print "A"
else
   If student's grade is greater or equal to 80
      Print "B"
   else
      If student's grade is greater or equal to 70
         Print "C"
      else
         Print "F"
[/pseudo_code]

4. while敘述式
如果有一支程式是輸入學生的成績直到輸入sentinel value停止,則虛擬碼的寫法 :
[pseudo_code]
Input the first grade
While the user has not as yet entered the sentinel
   Add this grade into the running total
   Add one to the grade counter
   Input the next grade
[/pseudo_code]

[Reference] :
C How to program 6/E

arrow
arrow

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()