C 語言中的逆向計數程式



逆向計數是按降序排列的連續整數序列,其中不包含零。在 C 程式語言中開發一個計數程式非常簡單,我們將在本章中看到這一點。

演算法

我們首先來看看逆向計數的分步過程 -

START
   Step 1 → Define start and end of counting
   Step 2 → Iterate from end to start
   Step 3 → Display loop value at each iteration
STOP

虛擬碼

現在我們來看該演算法的虛擬碼 -

procedure counting()

   FOR value = END to START DO
      DISPLAY value
   END FOR

end procedure

實現

現在,我們來看程式的實際實現 -

#include <stdio.h>

int main() {
   int i, start, end;

   start = 1;
   end = 10;

   //reverse counting, we'll interchange loop variables

   for(i = end; i >= start; i--) 
      printf("%2d\n", i);

   return 0;
}

輸出

該程式的輸出應為 -

10
 9
 8
 7
 6
 5
 4
 3
 2
 1
loop_examples_in_c.htm
廣告
© . All rights reserved.