C++陣列迭代程式
陣列是在記憶體中連續儲存的相同型別資料的集合。為了訪問或定址陣列,我們使用陣列的起始地址。陣列具有索引,我們可以使用索引訪問陣列的元素。在本文中,我們將介紹迭代陣列的方法。這意味著訪問陣列中存在的元素。
使用for迴圈
迭代陣列最常用的方法是使用for迴圈。在下面的示例中,我們將使用for迴圈遍歷陣列。需要注意的是,我們需要知道陣列的大小。
語法
for ( init; condition; increment ) { statement(s); }
演算法
- 輸入大小為n的陣列arr。
- 對於 i := 0 到 i := n,執行
- 列印 (arr[i])
示例
#include <iostream> #include <set> using namespace std; // displays elements of an array using for loop void solve(int arr[], int n){ for(int i = 0; i < n; i++) { cout << arr[i] << ' '; } cout << endl; } int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << "Values in the array are: "; solve(arr, n); return 0; }
輸出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
使用while迴圈
類似於for迴圈,我們可以使用while迴圈遍歷陣列。在這種情況下,也必須知道或確定陣列的大小。
語法
while(condition) { statement(s); }
演算法
- 輸入大小為n的陣列arr。
- i := 0
- 當 i < n 時,執行
- 列印 (arr[i])
- i := i + 1
示例
#include <iostream> #include <set> using namespace std; // displays elements of an array using for loop void solve(int arr[], int n){ int i = 0; while (i < n) { cout << arr[i] << ' '; i++; } cout << endl; } int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << "Values in the array are: "; solve(arr, n); return 0; }
輸出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
使用forEach迴圈
我們還可以使用現代的forEach迴圈來遍歷陣列中的元素。這種方法的主要優點是我們不需要知道陣列的大小。
語法
for (datatype val : array_name) { statements }
演算法
- 輸入大小為n的陣列arr。
- 對於每個元素 val in arr,執行
- 列印(val)
示例
#include <iostream> #include <set> using namespace std; int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; //using for each loop cout << "Values in the array are: "; for(int val : arr) { cout << val << ' '; } cout << endl; return 0; }
輸出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32
結論
本文介紹了在C++中迭代陣列的各種方法。前兩種方法的主要缺點是必須預先知道陣列的大小,但是如果我們使用forEach迴圈,則可以解決這個問題。forEach迴圈支援所有STL容器,並且更易於使用。
廣告