-1

I have a problem states:

WRITE A PROGRAM TO FIND THE MINIMUM NUMBER IN A LIST OF GIVEN N INTEGERS.

 #include<bits/stdc++.h>
 using namespace std;
 int FindIt (vector<int> arr)
 {
    **//WRITE YOUR CODE HERE`enter code here`**

 }
 int main()
 {
     ios::sync_with_stdio(0);
     cin.tie(0);
     int n;
     cin>>n;
     vector<int> arr(n);
     for(int i_arr=0;i_arr < n;i_arr++)
     {
         cin>>arr[i_arr];
     }
     int out_;
     out_ =FindIt(arr);
     cout<<out_;
 }

I tried running the program with the below approach but every time it shows 0 as output.

I don't know any other approach as i am a beginner.

 #include<bits/stdc++.h>
 using namespace std;
 int FindIt (vector<int> arr)
 {
     int min=0;
     int n=arr.size();
     int i;
     for(i=0;i<n;i++)
     {
         if(arr[i+1]<arr[i])
         min=arr[i+1];
     }
     return min;

 }
 int main()
 {
     ios::sync_with_stdio(0);
     cin.tie(0);
     int n;
     cin>>n;
     vector<int> arr(n);
     for(int i_arr=0;i_arr < n;i_arr++)
     {
         cin>>arr[i_arr];
     }
     int out_;
     out_ =FindIt(arr);
     cout<<out_;
 }
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

1 Answers1

1

The innocuously looking statement

 int min=0;

had introduced 0 as a value in your input. If all values in your input are increasing compared to preceding ones, the 0 is can be a "minimum" as the condition was never met. You have to compare vector element with current minimum, something like:

int min = arr[0];
for ( auto i = 1, n = arr.size(); i < n; i++)
   if(arr[i] < min)  
      min = arr[i];
Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42