I'm learning about arrays in my C++ class and am having some trouble with them. We have an assignment that states:

Write a program that will:

(1) Ask the user how many times a simulated pair of dice should be thrown.
(2) Ask whether the user wants to see each individual result. (With a large number of throws, the user may only want to see the final results.)
(3) "Throw" the dice the number of times requested, keeping track of the number of times each possible sum occurs.
(4) Display the final totals using a bar graph. A bar should be shown for the number of occurrences of each possible sum, from 2 to 12. Use a horizontal row of asterisks (or an appropriate graphics character) for each bar.
Your program should include a RollDie function. This function should pick random integer from 1 to 6 and return the result.
Use an array to keep track of how many times each sum occurred.

This is what I have:

``````#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;

int main()
{
int howmany, result1, result2, sum;
char response;
int total;
int RollDie(int result);

cout << "How many times would you like a pair of dice to be thrown? ";
cin >> howmany;
cout << "Would you like to see each individual result? (y or n) ";
cin >> response;

for (howmany=0;howmany<10;howmany++)
{
cout<<RollDie(result1);
cout<<RollDie(result2);
}

for (sum=0;sum<13;sum++)
{
sum = result1 + result2;
if (sum = 2)
total = 2;
if (sum = 3)
total = 3;
if (sum = 4)
total = 4;
if (sum = 5)
total = 5;
if (sum = 6)
total = 6;
if (sum = 7)
total = 7;
if (sum = 8)
total = 8;
if (sum = 9)
total = 9;
if (sum = 10)
total = 10;
if (sum = 11)
total = 11;
if (sum = 12)
total = 12;
}

getch();
return 0;
}

int RollDie(int result)
{
int result;

result = rand()%6;

return(result);
}``````

I'm sure there's a way to eliminate the if statements, but I'm drawing a blank. And I'm sure there's other mistakes within the program as well :( any help would be appreciated.

All you need to do is look through your if statements, and try to find a pattern or formula that can relate to all the values. When sum is 2, the array position is 0, and we input 2. When sum is 8, the array position is 6, and we input 8. Each if statement will do one of these, though they all follow the same pattern:
sum == sum ... array position = sum-2 ... input = sum

So:

``total[sum-2] = sum;``

Don't worry, I haven't written the code out for you. You will need to put this in a loop :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.