Description

Attempt to allocate memory for five variables of type integer (using the syntax malloc(5*sizeof(int))), then utilize a for loop to input five integer using the scanf() function. Afterward, compute their sum and the maximum value.

試以 malloc() 配置5個可存放 int 型態的變數(即利用malloc(5*sizeof(int))的語法)之記憶體空間,然後在for迴圈裡,分別以scanf() 函數輸入五個整數,最後再計算它們的總和與最大值。

請務必使用 malloc 配置記憶體 !!

Input

Input contains five integers.

輸入包含五個整數。

Output

Please calculate and print their sum and maximum value, separated by a space.

請計算並印出它們的總和與最大值,中間以空格分開。

Sample Input 1

Sample Output 1

1 3 9 5 7

9 25

Hint

此題修改自講義:【week 8】RefCh14memory_v1.6_20240410 P.17 第一小題。

#include <stdio.h>
#include <stdlib.h>

int main() {

    int sum = 0;
    int max;
//	malloc is in stdlib.h

    // use malloc 配置記憶體空間
    int *arr = (int*)malloc(sizeof(int));

    for (int i = 0; i < 5; i++) {
        scanf("%d", &arr[i]);
    }

    max = arr[0];
    for (int i = 0; i < 5; i++) {
        sum += arr[i];
        if (arr[i] > max) {
            max = arr[i];
        }
    }

    // free
    free(arr);

    // 輸出結果
    printf("%d %d\\n", max, sum);

    return 0;
}