Help with c++ vectors

Asked

Viewed 15 times

1

I need to create a program where give the lowest value and tell what position you are in, example

input: 4

     5,4,3,1

exit:

lower value : 1

position: 4

so far my code is like this and I have no idea how to continue

#include <iostream>

using namespace std;

int main() {
int n,i,menor ;

cin >> n;

int a[n];

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

for(int i=0; i<n ;i++){
if(a[i]<menor){
menor=a[i];
}
}

cout << menor << endl;


return 0;
}

1 answer

0

Instead of saving the value of the smallest keep the index of the smallest.

#include <iostream>
using namespace std;

int main() {
    int n,i,menor ;
    cin >> n;
    int a[n];
    for (int i = 0; i< n; i++){
        cin >> a[i];
    } 
    menor = 0;
    for(int i=1; i<n ;i++){
        if(a[i] < a[menor]){
            menor = i;
        }
    }
    cout << "Menor: "<< a[menor] << "\tÍndice: " << menor << endl;
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.