C++ Exercises: Compute the difference between the largest and smallest values in a given array of integers and length one or more
C++ Basic Algorithm: Exercise-99 with Solution
Write a C++ program to compute the difference between the largest and smallest values in a given array of integers and length one or more.
Sample Solution:
C++ Code :
#include <iostream>
using namespace std;
static int test(int nums[], int arr_length)
{
int small_num = 0, biggest_num = 0;
if (arr_length > 0) small_num = biggest_num = nums[0];
for (int i = 1; i < arr_length; i++)
{
small_num = min(small_num, nums[i]);
biggest_num = max(biggest_num, nums[i]);
}
return biggest_num - small_num;
}
int main()
{
int nums1[] = { 1, 5, 7, 9, 10, 12};
int arr_length = sizeof(nums1) / sizeof(nums1[0]);
cout << test(nums1, arr_length) << endl;
int nums2[] = {0, 2, 4, 6, 8, 10};
arr_length = sizeof(nums2) / sizeof(nums2[0]);
cout << test(nums2, arr_length) << endl;
return 0;
}
Sample Output:
11 10
Pictorial Presentation:
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to count even number of elements in a given array of integers.
Next: Write a C++ program to compute the sum of values in a given array of integers except the number 17. Return 0 if the given array has no integer.
What is the difficulty level of this exercise?