In: Computer Science
C++ PLEASE
Write a new program called Lab15A
Write a void function named fillArray that receives an
array of 10 integers as a parameter and fills the array by reading
the values from a text file (Lab15A.txt).
It should also print the values of the array all on the same line,
separated by spaces.
Write an int function named findLast that receives an array of 10 integers as a parameter and returns the last negative number in the array.
Write an int function named findSmallest that receives an array of 10 integers as a parameter and returns the smallest number in the array.
In your main method
Declare the array of 10 integers
Call fillArray, sending the array as a parameter.
Call findLast, sending the array as a parameter, and print the value it returns with a label.
Call findSmallest, sending the array as a parameter, and print the value it returns with a label.
I have implemented the following methods ::
1> void fillArray(int arr[]) : This function store integers into array from the "Lab15A.txt" file.
2> int findLast(int arr[]) : This function returns last negative number from the array otherwise return -1.
3> int findSmallest(int arr[]) : This function return smallest element from the array.
Here, #include<fstream> header file used to read integers from the "Lab15A.txt" file.
Program:-
#include<iostream>
#include<fstream>
using namespace std;
// This function store integers from txt file
void fillArray(int arr[]){
ifstream in("Lab15A.txt");
int cnt= 0;
int x;
// check that array is not already full
while (cnt < 10 && in >> x){
// and read integer from file
arr[cnt++] = x;
}
// print the integers stored in the array
cout<<"From filledArray() Array Values :"<<"\n";
for (int i = 0; i < cnt; i++) {
cout << arr[i] <<' ';
}
//close the file
in.close();
}
// This function returns last negative numbers otherwise returns -1.
int findLast(int arr[]){
int getLastNegative = -1;
bool found = false;
for (int i = 9; i >= 0; i++) {
if(arr[i] < 0){
//cout<<arr[i];
getLastNegative = arr[i];
found = true;
break;
}
}
if(found)
return getLastNegative;
else
return getLastNegative;
}
// This function find smallest from the array
int findSmallest(int arr[]){
int min = arr[0];
for(int i=1; i<10; i++){
if(arr[i] < min)
min = arr[i];
}
return min;
}
int main(){
int arr[10];
// call the fillArray()
fillArray(arr);
// call the findLast()
cout<<"\n\nLast Negative element from array : "<<findLast(arr);
// call findSmallest()
cout<<"\n\nFind Smallest : "<<findSmallest(arr);
return 0;
}
Output:-
I hope you will understand the above program.
Do you feel needful and useful then please upvote me.
Thank you.