write a main function to input 20 integers in the range of 1…

write a main function to input 20 integers in the range of 1 to 6.  write a function  count the number of times the numbers 2 and 5 occur.  the function should declare static variables count2 and count5.  check the data validity in the main function

Answer

In the given problem, we need to write a main function that inputs 20 integers in the range of 1 to 6. Additionally, we are required to write a function that counts the number of times numbers 2 and 5 occur. The function should declare static variables count2 and count5. It is also important to check the data validity in the main function to ensure the input integers are within the desired range.

Let’s start by writing the main function that will handle the input of 20 integers and check their validity:

“`c++
#include

void countOccurrences();

int main() {
int input;
for (int i = 0; i < 20; i++) { std::cout << "Enter an integer between 1 and 6: "; std::cin >> input;

// Check the validity of the input
while (input < 1 || input > 6) {
std::cout << "Invalid input! Please enter an integer between 1 and 6: "; std::cin >> input;
}

// If the input is valid, call the function to count occurrences
countOccurrences();
}

return 0;
}
“`

In the main function, we use a loop to iterate 20 times and prompt the user to enter an integer between 1 and 6. We then check the validity of the input using a while loop. If the input is valid, we call the countOccurrences() function.

Now let’s write the countOccurrences() function to count the number of occurrences of numbers 2 and 5:

“`c++
void countOccurrences() {
static int count2 = 0; // static variable to store the count of number 2
static int count5 = 0; // static variable to store the count of number 5

int number;
std::cout << "Enter a number: "; std::cin >> number;

// Check if the entered number is 2 or 5 and increment the respective count
if (number == 2) {
count2++;
} else if (number == 5) {
count5++;
}

// Output the counts of 2 and 5
std::cout << "Occurrences of 2: " << count2 << std::endl; std::cout << "Occurrences of 5: " << count5 << std::endl; } ``` In the countOccurrences() function, we use static variables to store the counts of numbers 2 and 5. This ensures that the variable values are retained across function calls. We take an integer input from the user and check if it is equal to 2 or 5. If it matches, we increment the respective count variable. Finally, we output the counts of numbers 2 and 5. By implementing this code, we can successfully input 20 integers in the range of 1 to 6, check their validity, and count the occurrences of numbers 2 and 5.

Do you need us to help you on this or any other assignment?


Make an Order Now