Hello, please divide this code snippet into functions, in a way, only functions
ID: 3545892 • Letter: H
Question
Hello, please divide this code snippet into functions, in a way, only functions are written in main() function.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice(); // Returns a random number ranged from 1-6
void no_Of_Occu(); // Returns the conditions and the result of occurances
int main()
{
no_Of_Occu();
}
int dice_Rnd_Numb()
{
int rnd_no;
return rnd_no = (rand() % 6) + 1;
}
void no_Of_Occu()
{
srand (time(NULL));
int throws_number;
do {
cout << "How many times you wanna throw the dice ? (Please enter a number greater than 10) : ";
cin >> throws_number;
}
while(throws_number<10);
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
int result;
for (int i = 0; i < throws_number; i++)
{
result = dice_Rnd_Numb();
if (result == 1)
a++;
else if (result == 2)
b++;
else if (result == 3)
c++;
else if (result == 4)
d++;
else if (result == 5)
e++;
else if (result == 6)
f++;
}
cout << "Number of occurrences of 1 was " << a << endl;
cout << "Number of occurrences of 2 was " << b << endl;
cout << "Number of occurrences of 3 was " << c << endl;
cout << "Number of occurrences of 4 was " << d << endl;
cout << "Number of occurrences of 5 was " << e << endl;
cout << "Number of occurrences of 6 was " << f << endl;
}
Explanation / Answer
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice(); // Returns a random number ranged from 1-6
void no_Of_Occu(); // Returns the conditions and the result of occurances
int main()
{
no_Of_Occu();
}
int throwDice()
{
int rnd_no;
return rnd_no = (rand() % 6) + 1;
}
void no_Of_Occu()
{
srand (time(NULL));
int throws_number;
do {
cout << "How many times you wanna throw the dice ? (Please enter a number greater than 10) : ";
cin >> throws_number;
}
while(throws_number<10);
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
int result;
for (int i = 0; i < throws_number; i++)
{
result = throwDice();
if (result == 1)
a++;
else if (result == 2)
b++;
else if (result == 3)
c++;
else if (result == 4)
d++;
else if (result == 5)
e++;
else if (result == 6)
f++;
}
cout << "Number of occurrences of 1 was " << a << endl;
cout << "Number of occurrences of 2 was " << b << endl;
cout << "Number of occurrences of 3 was " << c << endl;
cout << "Number of occurrences of 4 was " << d << endl;
cout << "Number of occurrences of 5 was " << e << endl;
cout << "Number of occurrences of 6 was " << f << endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.