C語言入門-數組
- 2019 年 10 月 3 日
- 筆記
今天十月一日,上午看閱兵激情澎湃,但是下午還是要繼續寫C語言,前面的這塊很簡單
int number[100]; scanf("%d" , &number[i]);
一、定義數組
- <類型> 變量名稱[元素數量]
- 元素數量必須是整數
數組特點
- 所有的元素具有相同的數據類型
- 一旦創建,就不能改變大小
- (數組中的元素在內存中是連續以此排序的)
二、數組例子
寫一個程序,輸入數量不確定的[0,9]範圍內的整數,統計每一種數字出現的次數,輸入-1表示結束
通常用到數組都是下面的步驟:
#include <stdio.h> int main(void) { // 數組的大小 const int number = 10; int x; // 定義數組 int count[number]; int i; // 初始化數組 for (i = 0; i < number; i++) { count[i] = 0; } scanf("%d" , &x); while( x != -1){ if(x >= 0 && x <= 9){ // 數組參與運算 count[x] ++; } scanf("%d" , &x); } // 遍曆數組輸出 for (i = 0; i < number; i++) { printf("%d:%dn", i , count[i]); } return 0; }
三、數組運算
數組的集成初始化
int a[] = {2,4,6,7,1,3,5,9,11,13,23,14,32};
集成初始化時定位
int a[10] = {[0] = 2 , [2] = 3,6}; int i; for (i = 0; i < 10; ++i) { printf("%dt", a[i]); } // 2 0 3 6 0 0 0 0 0 0
- 用[n]在初始化數據中給出定位
- 沒有定位的數據接在前面的位置後面
- 其他位置的值補零
- 也可以不給出數組大小,讓編譯器算
- 特別適合初始數據稀疏的數組
數組大小
- sizeof給出整個數組所佔據的內容的大小,單位是位元組
sizeof(a)/sizeof(a[0]);
- sizeof(a[0])給出數組中單個元素的大小,於是相除就得到了數組的單元個數
- 這樣的代碼,一旦修改數組中的初始的數據,不需要修改遍歷的代碼
數組的賦值
- 數組變量本身不能被賦值
- 要把一個數組的所有元素交給另一個數組,必須採用遍歷
四、數組中查找元素
數組作為函數參數時,往往必須再用另一個參數來傳入數組的大小
數組作為函數的參數時:
- 不能在[]中給出數組的大小
- 不能再利用sizeof來計算數組的元素個數
#include <stdio.h> int main(void) { int a[] = {2,4,6,7,1,3,5,9,11,13,23,14,32,}; int x; int loc; printf("請輸入一個數字:n"); scanf("%d" , &x); loc = search(x, a, sizeof(a)/sizeof(a[0])); if (loc != -1) { printf("%d在第%d個位置上n", x , loc); }else{ printf("%d不存在n", x); } return 0; } int search(int key , int a[] , int length) { int ret = -1; int i; for (i = 0; i < length; i++) { if (a[i] == key) { ret = i; break; } } return ret; }
五、素數
判斷是否能被已知的且<x的素數整除
#include <stdio.h> int main(void) { const int number = 10; int prime[10] = {2}; int count = 1; int i = 3; while(count < number){ if (isPrime(i,prime,count)) { prime[count++] = i; } // 進行調試 { printf("i=%d tcnt=%dt", i , count ); int i; for (i = 0; i < number; i++) { printf("%dt", prime[i]); } printf("n"); } i++; } for ( i = 0; i < number; i++) { printf("%d", prime[i]); if ( (i+1)%5) { printf("t"); }else{ printf("n"); } } return 0; } int isPrime(int x, int knownPrimes[], int numberofKnowPrimes) { int ret = 1; int i; for (i = 0; i <numberofKnowPrimes ; i++) { if ( x % knownPrimes[i] == 0) { ret = 0; break; } } return ret; }
六、二維數組
int a[3][5] // 通常可以理解為a是一個3行5列的矩陣
二維數組的遍歷
for(i = 0; i<3; i++){ for(j = 0; j<5; j++){ a[i][j] = i * j; } } // a[i][j]是一個int,表示第i行第j列上的單元
二維數組的初始化
int a[][5] = { {0,1,2,3,4,}, {2,3,4,5,6,}, };
- 列數是必須給出的,行數可以有編譯器來定
- 每行一個{},逗號分隔
- 最後的逗號可以存在
- 如果省略,表示補零