I've been trying to get into coding and need some help with my code. I figured out how to get the maximum difference, but I also want to print the numbers used to get that difference. For example, a-b=diff, I want to print a, b, and diff separately. My friend also challenged me to get the smaller value first, then get the bigger value. Now, once I pick a certain element in the array as the smallest number, I'm only allowed to pick through the next elements for the biggest number. For example, if the array is {2, 3, 4, 15, 8, 1}, it should be 15 - 2, not 15 - 1.
Here is my code to get the maximum difference/what I have so far:
#include <iostream>
using namespace std;
int maximum_difference(int arr[], int n)
{
int max_num = arr[1];
int min_num = arr[0];
int max_difference = max_num - min_num;
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (arr[j] - arr[i] > max_difference)
{
max_num=arr[j];
min_num=arr[i];
max_difference = max_num - min_num;
}
}
}
return max_difference;
}
int main()
{
int n;
cout<<"elements: ";
cin >> n;
int arr[n];
for(int i=0; i<n; i++)
{
cin >> arr[i];
}
cout << "Maximum difference is " << maximum_difference(arr, n);
return 0;
}
What should I add or replace, so that I could cout max_num and min_num together with the max_difference?