i've been assigned to write a program in C++ that, given an array of integers, finds the smallest (including its index) and largest number, and their subtraction. To do this, i decided to write three functions for each operation and it works perfectly. The problem is i don't know how to get the index of the smallest number.
I tried solving the problem by creating a variable and putting in inside a for loop and then print it. However, the program always says the index is 0.
Here you can see an example of how the output should be:
int myvector[200] = {40, 250, 9, 50} // Array containing 4 numbers
It should output:
The smallest number is: 9 at index 2
The largest number is: 250
Their subtraction is: 241
Here you can see my code:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int find_smallest (int myvector[], int smallest, int index){
smallest = myvector[0];
index = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] < smallest) {
smallest = myvector[i];
index = i;
}
}
return smallest;
}
int find_largest (int myvector[], int largest) {
largest = myvector[0];
for(int i=0; i<4; i++) {
if(myvector[i] > largest) {
largest = myvector[i];
}
}
return largest;
}
int sub_minmax (int myvector[], int subtraction, int smallest, int largest){
subtraction = largest - smallest;
return subtraction;
}
int main()
{
int myvector[200], smallest, largest, subtraction, index;
for(int i=0;i<4; i++) {
cout<<"Enter the number " <<i+1<<endl;
cin>>myvector[i];
}
smallest = find_smallest(myvector, smallest, index);
largest = find_largest(myvector, largest);
subtraction = sub_minmax(myvector, subtraction, smallest, largest);
cout<<endl;
cout<<"the smallest number is: "<<smallest<<" at index "<<index<<endl;
cout<<"the largest number is: "<<largest<<endl;
cout<<"the substraction is: "<<subtraction<<endl;
return 0;
}
Any help will be appreciated, thanks
indexby reference.