數組

幾種寫法:

   int ages[5] = {10 , 11, 12, 67, 56};
   int ages[5] = {10, 11};
   int ages[5] = {[3] = 10, [4] = 11};
   int ages[] = {10, 11, 14};

int main()
{
    // 數組的定義格式: 類型 數組名[元素個數];
    int ages[5] = {19, 29, 28, 27, 26};
    // 19 19 28 27 26]
    ages[1] = 29;
    
    /*
     ages[0] = 19;
     ages[1] = 19;
     ages[2] = 28;
     ages[3] = 27;
     ages[4] = 26;
     */
    
    /*
     遍歷:按順序查看數組的每一個元素
     */
    for (int i = 0; i<5; i++)
    {
        printf("ages[%d]=%d\n", i, ages[i]);
    }
}


練習:設計一個函數,找出整型數組元素的最大值


#include <stdio.h>


int maxOfArray(int array[], int length)
{
    // 數組當做函數參數傳遞時,會當做指針變量來使用,指針變量在64bit編譯器環境下,佔據8個字節
    
    //int size = sizeof(array);
    //printf("array=%d\n", size);
    
    //sizeof(array);
    
    // 1.定義一個變量存儲最大值(默認就是首元素)
    int max = array[0];
    
    // 2.遍歷所有元素,找出最大值
    for (int i = 1; i<length; i++)
    {
        // 如果當前元素大於max,就用當前元素覆蓋max
        if (array[i] > max)
        {
            max = array[i];
        }
    }
    
    return max;
}


int main()
{
    int ages[] = {11, 90, 67, 150, 78, 60, 70, 89, 100};
    
    int ages2[] = {11, 90, 67, 150, 78, 60, 70, 89, 100};
    
    //int size = sizeof(ages);
    
    //printf("ages=%d\n", size);
    int max = maxOfArray(ages, sizeof(ages)/sizeof(int));
    
    printf("%d\n", max);
    return 0;
}


發佈了59 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章