In: Computer Science
Write the following task in C++
1) Write the definition of a function numOccurrences that searches for a character in a character array and returns the number of times it occurs in the array. The function has three formal parameters: a char array array, an int variable arraySize representing the size of the array, and a character variable letter representing the character to be searched for in the array.
2) Assume the array numbers is an int array of size 10 and the array has been initialized, write C++ statements to find and output the smallest element of the array as well as the position of the smallest element in the array
---------q1.cpp----------------
#include
using namespace std;
//This function searches for a character in a character array
and returns the number of times it occurs in the array
int numOccurrences(char array[], int arraySize, char c)
{
int count = 0;
for(int i = 0; i < arraySize; i++)
//loop for all the indexes of array
{
if(array[i] == c){
//check if chracter at index i matches c
count++; //then increment the
count
}
}
return count; //return the count
}
int main()
{
char array[10] = {'h', 'e', 'l', 'l', 'o', 'w', 'o',
'r', 'l', 'd'}; //declare char array
cout << "The array is: ";
for(int i = 0; i < 10; i++)
{
cout << array[i] << ",
"; //print the array
}
//test the function numOccurrences by calling
it
cout << "\nThe number of occurrences of 'e' = "
<< numOccurrences(array, 10, 'e');
cout << "\nThe number of occurrences of 'o' = "
<< numOccurrences(array, 10, 'o');
cout << "\nThe number of occurrences of 'd' = "
<< numOccurrences(array, 10, 'd');
cout << "\nThe number of occurrences of 't' = "
<< numOccurrences(array, 10, 't') << endl;
return 0;
}
---------q2.cpp----------------
#include
using namespace std;
int main()
{
int numbers[10] = {10, 12, 19, 22, 3, 33, 4444, 34,
9333, 93}; //int array of size 10 and the array has been
initialized
cout << "\nThe array is: ";
for(int i = 0; i < 10; i++)
{
cout << numbers[i] <<
", "; //print the array
}
int smallest_element = numbers[0];
//initialize smallest element to index 0 element of array
int smallest_index = 0;
//initialize smallest index
to index 0
for(int i = 1; i < 10; i++)
//loop from index 1 to the
last index of array
{
if(numbers[i] <
smallest_element){ //check if element at index i is
smaller than the smallest_element
smallest_element
= numbers[i]; //update the smallest_element and
smallest_index
smallest_index =
i;
}
}
//print the smallest element and the index
cout << "\nThe smallest element of the array is
" << smallest_element << endl;
cout << "The smallest element is present at
index " << smallest_index << endl;
return 0;
}
--------Screenshots---------------
--------Outputs---------------