In: Computer Science
Part B)
Write a C++ program which prompts user to choose from the two alternative funtions specified below, each of which passes a random number between 1 and 4 and returns a random message.
The two functions are:
Function messageByValue that passes a random value between 1 and 4
and returns the message by value and
Function messageByReference that passes a random value between 1
and 4 and returns the message by reference.
Each function returns one of four random messages:
- “Sorry. You’re busted!”
- “Oh, you’re going for broke, huh?”
- “Aw cmon, take a chance!”
- You’re up big. Now’ the time to cash in your chips”
NOTE:
Use a while loop to continually run program until a -1 is entered
to Terminate program.
Solution for the given question are as follows -
Code :
#include<iostream>
#include <stdlib.h>
using namespace std;
// messageByReference - return message by reference
string &messageByReference (string s[], int x)
{
return s[x];
}
// messageByValue - return message by value
string messageByValue(string s[],int x)
{
return s[x];
}
int main()
{
// variable declaration
int n;
string s, str[4] = {"Sorry. You’re busted!", "Oh, you’re going for
broke, huh?", "Aw cmon, take a chance!", "You’re up big. Now’ the
time to cash in your chips"};
// infinite loop
do {
cout << "Enter your choice: \n";
cout << "1. MessageByValue: \n";
cout << "2. MessageByReference : \n";
cout << "Exit -1 \n";
cin >> n;
// get random number
int x = rand() % 3;
switch (n) {
case 1 :
// call to function and pass array of string and random
number
s = messageByValue(str,x);
cout<<s<<"\n";
break;
case 2 :
s = messageByReference(str,x);
cout<<s <<"\n";
break;
case -1 :
exit(0);
break;
default:
cout<<"Invalid choice\n";
break;
}
} while (n != -1);
return 0;
}
Code Screen Shot :
Output :