Max
Learning Goals
- Pass an array into a function
- Create a helper function that finds a maximum value
背景
There are many situations where you’ll find it helpful to have a function that finds the maximum (and minimum) value in an array. Since there is no built-in max function in C, you’ll create one in this 练习题. You can then use it in upcoming 问题集 where it可能是 helpful!
- 提示
- Start out with a variable that keeps track of your max value. There are two ways to initialize this. You can start out using the lowest possible value (be careful you don’t start with zero, as the max value could be a negative number!) or you can start with the first element in the array.
- Loop through the array and reset this max value every时间 you find a value that’s larger.
演示
入门
- Log into cs50.dev using your GitHub account.
- Click inside the terminal window and execute
cd. - Execute
wget https://cdn.cs50.net/2022/fall/实验s/3/max.zipfollowed by Enter in order to 下载 a zip calledmax.zipin your codespace. Take care not to overlook the space betweenwgetand the following URL, or any other character for that matter! - Now execute
unzip max.zipto create 的文件夹中名为max. - You 不再 need the ZIP file, so you can execute
rm max.zipand respond with “y” followed by Enter at the prompt.
实现细节
The main function initializes the array, asks the user to enter values, and then passes the array and the number of items to the max function. Complete the max function by iterating through every element in the array, and return the maximum value.
Thought 问题
- What types of programs can you think of that might benefit from a
maxhelper function?
如何测试 Your Code
你的程序应该 behave per the例子below.
max/ $ ./max
Number of elements: 3
Element 0: 2
Element 1: 10
Element 2: -1
The max value is 10.
max/ $ ./max
Number of elements: 4
Element 0: -100
Element 1: -200
Element 2: -3
Element 3: -5000
The max value is -3.
You can check your code using check50, a program that CS50 will use to test your code when you 提交, by typing in the following at the $ prompt. But be sure to test it自己 as well!
check50 cs50/实验s/2023/x/max
To evaluate that the style of your code, type in the following at the $ prompt.
style50 max.c
如何提交
No need to 提交! This is an 可选 练习题.