-2

I tried changing a lot of integers and stuff but it didn't work and it gives me a random number like 53289432 even tho lets say i put in 3:5,1,2 it should output 3 since 5-2 is 3.

#include <iostream>

using namespace std;

int main()
{
 int n;
 cin>>n;
 int x[n];
 int mn;
 int mx;

 for(int i=1;i<n;i++)
 {
     cin>>x[i];
     for(int j=1;j<n;j++)
     {
     if(x[i]>x[j]);
     }
 {
    x[i]=mn;
 }
 }
  for(int i=1;i<n;i++)
 {
    
   for(int j=1;j<n;j++)
     {
     if(x[i]<x[j]);
     }
 {
    x[i]=mx;
 }
 }
 cout<<mx-mn;
 
 
 
}
user438383
  • 5,716
  • 8
  • 28
  • 43
hazey
  • 9
  • 3

2 Answers2

1

You don't need an array:

int smallest = 0;
int largest  = 0;
std::cout << "Enter quantity: ";
int quantity;
std::cin >> quantity;
if (quantity < 1)
{
  std::cerr << "Invalid quantity.\n";
  return 1;
}
std::cout << "Enter number: ";
std::cin >> smallest;
largest = smallest;
for (int i = 1; i < quantity; ++i)
{
  std::cout << "Enter number: ";
  int number;
  std::cin >> number;
  if (number < smallest) smallest = number;
  if (number > largest)  largest  = number;
}
std::cout << "maximum from minimum: " << (smallest - largest) << "\n";
std::cout << "minimum from maximum: " << (largest - smallest) << "\n";

The above code uses a running minimum/maximum, so no arrays are needed.

No need for variable length arrays or having to figure out the array capacity at compile time.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

Your code carries several holes,

Firstly,

for(int i=1;i<n;i++)
{ 
  cin>>x[i];

This won't take n integers, it will only take (n-1) integers as input. You need to initialise i=0, for n integers;

Secondly,

for(int i=1;i<n;i++)
{
   cin>>x[i];
   for(int j=1;j<n;j++)
   {
     if(x[i]>x[j]); //This will compare with garbage when i=1 and j>1
   }
   {
     x[i]=mn;
   }
}

Your comparison, will only be valid for first iteration of i=1 and j=1, after j>1, it will pick garbage value, since, you haven't taken any input yet.

It is suggested, to first take all the inputs, then do the comparison, or other operations.

Here is my solution

I think this is what you are trying to do!

#include <iostream>
#include <climits>

using namespace std;

int main()
{
  int n;
  cin>>n;
 
  int x[n];
  int mn;
  int mx;
  
  //First take the inputs in array x

  for(int i=0;i<n;i++)
  {
     cin>>x[i];
  }

  //Find maximum and store it in mx

  mx = INT_MIN; //This stores minimum in mx variable (climits)
  for(int j=0;j<n;j++)
  {
     if(mx<x[j])
       mx=x[j];
  }

  //Find minimum and store it in mn

  mn = INT_MAX; //This stores maximum in mn variable (climits)
  for(int j=0;j<n;j++)
  {
     if(mn>x[j])
       mn=x[j];
  }
  int ans = mx - mn;
  cout<<ans<<endl;
 
}

There is a better solution where you don't use extra space(array), and by using only 2 variables, you can find the difference. But I would recommend you to first understand this concept, and take a look, how array works, before moving towards any optimised solution.