C 語言中列印逆序陣列的程式



要按逆序列印陣列,我們需要預先知道陣列的長度。然後,我們可以從陣列的長度值開始迭代到 0,並且在每次迭代中,都可以列印陣列索引的值。此陣列索引應直接從迭代本身匯出。

演算法

讓我們首先看看該程式的分步過程−

START
   Step 1 → Take an array A and define its values
   Step 2 → Loop for each value of A in reverse order 
   Step 3 → Display A[n] where n is the value of current iteration
STOP

虛擬碼

現在讓我們看看此演算法的虛擬碼−

procedure print_array(A)

   FOR from array_length(A) to 0
      DISPLAY A[n]
   END FOR
   
end procedure

實現

以上述虛擬碼為基礎的實現如下−

#include <stdio.h>

int main() {
   int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
   int loop;

   for(loop = 9; loop >= 0; loop--)
      printf("%d ", array[loop]);
      
   return 0;
}

輸出應如下所示 −

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