Expecting your tips&hints

I want to write a code where will be given n integer numbers.The program will print the two numbers whose difference is the closest.It will show any two, if there are many numbers giving the same minimum difference.
I wrote a code but I don't get the desired result.Would you give me some help? :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>
using namespace std;

int main ()
{
    int n,max,num,difference;
    cin >> n >> max;
    for (int i=1;i<=n-1;i++)
    {
        cin >> num;
        if (num>max) {max=num;
        difference=num-max;
    }
    cout << max << " " << num << " " << difference;
    return 0;
}
}
You have to store those n numbers. I would put them into std::vector.

Sort the numbers. See http://www.cplusplus.com/reference/algorithm/sort/

Calculate adjacent differences. See http://www.cplusplus.com/reference/numeric/adjacent_difference/

Find minimum difference. See http://www.cplusplus.com/reference/algorithm/min_element/

Show corresponding values. See http://www.cplusplus.com/reference/iterator/distance/
Learn to indent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main ()
{
	int n,max,num,difference;
	cin >> n >> max;
	for (int i=1;i<=n-1;i++)
	{
		cin >> num;
		if (num>max) {
			max=num;
			difference=num-max; //num - num == 0
		}
		cout << max << " " << num << " " << difference;
		return 0;
	}
}
you'll read two numbers and your program would terminate.

Also explain what you are trying to do in that if block.
this code doesn't give the right output.. :/
that was your code, I just indent it properly.
Topic archived. No new replies allowed.