Write a C++ program to run a menu-driven program with the following choices:
#include <iostream> using namespace std; void getValidUserInputPosNumGT0 (int *a) { int num; cout << "Enter in a positive number greater than 0... "; cin >> *a; } long double factorial (int num) { int fact = 1; while (num > 1) { fact *= num; num--; } return fact; } long double AlternatingFactorial (int num) { int fact = 1; while (num < 1) { fact *=num; num++; } } int main (){ int ch; int num; cout << "Welcome to the playing with numbers program!\n"; do { cout << "1)Compute the factorial of a number\n"; cout << "2) Compute the alternating factorial of a number\n"; cout << "3)Quit\n"; while (true) { cout << "Select an option (1..3).."; cin >> ch; if (ch == 1 || ch == 2 || ch == 3) { break; } } switch (ch) { case 1: getValidUserInputPosNumGT0(&num); cout << "Factorial("<<num<<")="<< factorial(num) << endl; case 2: long double AlternatingFactorial (int num); cout << "AlternatingFactorial" << num << AlternatingFactorial(num)<< endl; } } while (ch!=3); return 0; }
I've tried to run this and option one works, but the alternating factorial (option 2) won't run.
#include <iostream>
using namespace std;
void getValidUserInputPosNumGT0 (int *a) {
int num;
cout << "Enter in a positive number greater than 0...
";
cin >> *a;
}
long double factorial (int num) {
int fact = 1;
while (num > 1) {
fact *= num;
num--;
}
return fact;
}
long double AlternatingFactorial (int num) {
int res=0;
for(int m=1;m<=num;m++){
if((num-m)%2==0){
res=res+factorial(m);
}
else{
res=res-factorial(m);
}
}
return res;
}
int main (){
int ch;
int num;
cout << "Welcome to the playing with numbers
program!\n";
do {
cout << "1)Compute the factorial of a number\n";
cout << "2) Compute the alternating factorial of a
number\n";
cout << "3)Quit\n";
while (true) {
cout << "Select an option (1..3)..";
cin >> ch;
if (ch == 1 || ch == 2 || ch == 3) {
break;
}
}
switch (ch) {
case 1:
getValidUserInputPosNumGT0(&num);
cout << "Factorial("<<num<<")="<<
factorial(num) << endl;
break;
case 2:
getValidUserInputPosNumGT0(&num);
cout << "AlternatingFactorial(" << num
<<")="<< AlternatingFactorial(num)<< endl;
}
} while (ch!=3);
return 0;
}
Note:
The return value is not provided in the function AlternatingFactorial(). So it is modified. And the errors in the switch case statements are removed.
Screenshots:
The screenshots are attached below for reference.
Please follow them for output.
Get Answers For Free
Most questions answered within 1 hours.