/ src / Focused 5 / f5.cpp
f5.cpp
 1  /*
 2  * FILE : f5.cpp
 3  * PROJECT : SENG1000 - FOCUSED ASSIGNMENT 5
 4  * PROGRAMMER : Tian Yang
 5  * FIRST VERSION : 2024-02-21
 6  * DESCRIPTION :
 7  * This program get integers from the user and determines which is the highest value.
 8  */
 9  
10  #include <stdio.h>
11  #include <limits.h>
12  
13  #define ARRAY_LENGTH 10 // Define a macro as the number of loops and array length.
14  
15  void modifyArrayValues(int[], int);
16  int maxArrayValue(int[], int);
17  int getNum(void);
18  
19  int main(int argc, char* argv[])
20  {
21  	int numArray[ARRAY_LENGTH] = { 0 };
22  	modifyArrayValues(numArray, ARRAY_LENGTH);
23  	int index = maxArrayValue(numArray, ARRAY_LENGTH);
24  	printf("The highest value is %d at index %d", numArray[index], index);
25  
26  	return 0;
27  }
28  
29  //
30  // FUNCTION : modifyArrayValues
31  // DESCRIPTION :
32  // This function prompts the user to enter numbers and store them in an array.
33  // PARAMETERS :
34  // int[] : array for numbers.
35  // int : length of the array.
36  // RETURNS :
37  // void : nothing to return.
38  //
39  void modifyArrayValues(int array[], int length)
40  {
41  	printf("Please enter %d integers, pressing ENTER after each one:\n", length);
42  	for (int i = 0; i < length; i++)
43  	{
44  		array[i] = getNum();
45  	}
46  }
47  
48  //
49  // FUNCTION : maxArrayValue
50  // DESCRIPTION :
51  // This function finds the highest value in an array.
52  // PARAMETERS :
53  // int[] : array for numbers.
54  // int : length of the array.
55  // RETURNS :
56  // int : index of the max number.
57  //
58  int maxArrayValue(int array[], int length)
59  {
60  	int index = 0;
61  	for (int i = 1; i < length; i++)
62  	{
63  		if (array[i] > array[index])
64  		{
65  			index = i;
66  		}
67  	}
68  	return index;
69  }
70  
71  //
72  // FUNCTION : getNum
73  // DESCRIPTION :
74  // This function gets user-entered number.
75  // PARAMETERS :
76  // void : nothing input.
77  // RETURNS :
78  // int : return the number that user entered.
79  //
80  #pragma warning(disable: 4996)
81  int getNum(void)
82  {
83  	/* we will see in a later lecture how we can improve this code */
84  	char record[121] = { 0 }; /* record stores the string */
85  	int number = 0;
86  	/* NOTE to student: indent and brace this function consistent with
87  	your others */
88  	/* use fgets() to get a string from the keyboard */
89  	fgets(record, 121, stdin);
90  	/* extract the number from the string; sscanf() returns a number
91  	* corresponding with the number of items it found in the string */
92  	if (sscanf(record, "%d", &number) != 1)
93  	{
94  		/* if the user did not enter a number recognizable by
95  		* the system, set number to -1 */
96  		number = -1;
97  	}
98  	return number;
99  }