20.4k views
3 votes
Write a C++ program that loops forever and asks the user to enter 3 positive numbers c1, c2, and c3 that are in the range [1, 20] for c1, and [1, 100] for c2 and c3. The interval [] is closed; which means the 1, 20, and 100 are included. Check for invalid values for c1, c2, and c3, and continue to the beginning of the loop if any value is invalid. The main program calls a function: void type_table(size_c first, size_c mid, size_tclast); This function will write to screen the multiplication table for num from first to last. Ask the user if they want to repeat at the end of the while loop.

1 Answer

4 votes

Final answer:

To write a C++ program that loops forever and asks the user to enter 3 positive numbers within specific ranges, you can use a while loop and if statements for validation. You can generate random numbers using the 'rand' function, and call a function to display the multiplication table. The program can be repeated based on user input.

Step-by-step explanation:

To write a C++ program that loops forever and asks the user to enter 3 positive numbers within specific ranges, you can use a while loop. Inside the loop, you can prompt the user for input and validate the values using if statements. If any value is invalid, you can use the 'continue' keyword to go back to the beginning of the loop. Once all values are valid, you can call the function 'type_table' to write the multiplication table to the screen.

To generate random numbers within the specified ranges, you can use the 'rand' function and then scale the result to fit the desired range using modulus and addition operators. Here's a sample code:

#include <iostream>
#include <cstdlib>

using namespace std;

void type_table(size_t first, size_t mid, size_t last) {
for (size_t num = first; num <= last; num++) {
for (size_t i = mid; i <= last; i++) {
cout << num << " * " << i << " = " << num * i << endl;
}
}
}

int main() {
while (true) {
size_t c1, c2, c3;
cout << "Enter three positive numbers: ";
cin >> c1 >> c2 >> c3;

if (c1 < 1 || c1 > 20) {
cout << "c1 is invalid. Enter a number between 1 and 20." << endl;
continue;
}

if (c2 < 1 || c2 > 100) {
cout << "c2 is invalid. Enter a number between 1 and 100." << endl;
continue;
}

if (c3 < 1 || c3 > 100) {
cout << "c3 is invalid. Enter a number between 1 and 100." << endl;
continue;
}

type_table(c1, c2, c3);

char repeat;
cout << "Do you want to repeat? (y/n): ";
cin >> repeat;

if (repeat != 'y' && repeat != 'Y') {
break;
}
}

return 0;
}

User Malte Onken
by
8.1k points