In: Computer Science
Write a C++ function, smallestIndex, that takes as parameters an int array and its size and returns the index of the first occurrence of the smallest element in the array. Also, write a program to test your function.
You must write our commands in the middle:
Write a C++ Program:
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 15;
void printArray(const int x[], int sizeX);
int smallestIndex(const int x[], int sizeX);
int main()
{
int list[ARRAY_SIZE] = {56, 34, 67, 54, 23, 87, 66, 92, 15, 32,
55, 54, 88, 22, 30};
…
…
YOUR CODE HERE
…
…
return 0;
}
//Function to print the array
void printArray(const int list[], int listSize)
{
int index;
for (index = 0; index < listSize; index++)
cout << list[index] << " ";
}
// Function to find and return the index of the
// smallest element of an array
int smallestIndex(const int list[], int listSize)
{
…
…
YOUR CODE HERE
…
…
}
I have completed the code in C++
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 15;
void printArray(const int x[], int sizeX);
int smallestIndex(const int x[], int sizeX);
int main(){
int list[ARRAY_SIZE] = {56, 34, 67, 54, 23, 87, 66, 92, 15, 32, 55, 54, 88, 22, 30};
printArray(list, ARRAY_SIZE);
// printing the index of smallestElement
cout<<"\nThe index of the first occurence of smallest element is: "<<smallestIndex(list, ARRAY_SIZE);
return 0;
}
//Function to print the array
void printArray(const int list[], int listSize){
int index;
for (index = 0; index < listSize; index++)
cout << list[index] << " ";
}
// Function to find and return the index of the smallest element of an array
int smallestIndex(const int list[], int listSize){
int smallestElement=1000000;
// finding the smallestElement
for(int i = 0; i<ARRAY_SIZE; i++){
if(list[i]<smallestElement)
smallestElement=list[i];
}
// finding the first occurence of smallestElement
for(int i = 0; i<ARRAY_SIZE; i++){
if(list[i]==smallestElement)
return i;
}
}
Here the smallest element is 15 and its index is 8 so the function is working perfectly fine.
i have added comments so that you can understand better.
If you like the answer then please upvote.