陣列是一組以單一名稱儲存的相關資料項目。
例如int Student[30]; //student是一個陣列名,包含單一變數名的30個資料項集合
搜尋 - 用於尋找特定元素是否存在
#排序 - 它有助於排列數組中的元素按升序或降序排列。
遍歷 - 它按順序處理陣列中的每個元素。
插入 - 它有助於在陣列中插入元素。
刪除 - 它有助於刪除陣列中的元素。數組中的元素。
在陣列中找出偶數的邏輯如下-
for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } }
在陣列中尋找奇數的邏輯如下-
for(i = 0; i < size; i ++){ if(a[i] % 2 != 0){ odd[Ocount] = a[i]; Ocount++; } }
要顯示偶數,請呼叫下面提到的顯示函數-
printf("no: of elements comes under even are = %d </p><p>", Ecount); printf("The elements that are present in an even array is: "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("</p><p>"); }
要顯示奇數,請依照下列方式呼叫顯示函數−
printf("no: of elements comes under odd are = %d </p><p>", Ocount); printf("The elements that are present in an odd array is : "); void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("</p><p>"); }
以下是使用for 迴圈分隔數組中偶數和奇數的C 程式-
現場示範
#include<stdio.h> void display(int a[], int size); int main(){ int size, i, a[10], even[20], odd[20]; int Ecount = 0, Ocount = 0; printf("enter size of array :</p><p>"); scanf("%d", &size); printf("enter array elements:</p><p>"); for(i = 0; i < size; i++){ scanf("%d", &a[i]); } for(i = 0; i < size; i ++){ if(a[i] % 2 == 0){ even[Ecount] = a[i]; Ecount++; } else{ odd[Ocount] = a[i]; Ocount++; } } printf("no: of elements comes under even are = %d </p><p>", Ecount); printf("The elements that are present in an even array is: "); display(even, Ecount); printf("no: of elements comes under odd are = %d </p><p>", Ocount); printf("The elements that are present in an odd array is : "); display(odd, Ocount); return 0; } void display(int a[], int size){ int i; for(i = 0; i < size; i++){ printf("%d \t ", a[i]); } printf("</p><p>"); }
執行上述程序時,會產生以下結果-
enter size of array: 5 enter array elements: 23 45 67 12 34 no: of elements comes under even are = 2 The elements that are present in an even array is: 12 34 no: of elements comes under odd are = 3 The elements that are present in an odd array is : 23 45 67
以上是如何使用C語言中的for迴圈將陣列中的偶數和奇數分開?的詳細內容。更多資訊請關注PHP中文網其他相關文章!