Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Counted Bag Write a C++ program that will create a bag and put in 30,000 random

ID: 3663476 • Letter: C

Question

Counted Bag

Write a C++ program that will create a bag and put in 30,000 random integers in the range from 0 to 19 (inclusive). Then the program will print a table of the bag counts for each number from 0 to 19. • Increase the CAPACITY of bag to 30,000

> Use CAPACITY instead of directly using 30,000 in the program

•Use a variable to hold the range of values to use.

> The value of the variable will be 20 for a range of numbers from 0 to 19 (inclusive)

•The rand()function is in cstdlib

> rand()returns non-negative integers so the % operator will give you values in the proper range

• Use setw()in the output, from iomanip, to line up the output in neat columns

Sample output:

0 1481

1 1538

2 1442

3 1504

4 1478

5 1546

6 1503

7 1499

8 1547

9 1505

10 1475

11 1463

12   1504

13 1586

14 1469

15 1508

16 1511

17 1466

18 1502

Explanation / Answer

#include<iostream>
#include<cstdlib>
#include<iomanip>

using namespace std;

int main() {
  
   const int CAPACCITY = 30000;
   const int LOW = 0;
   const int HIGH = 19;
  
   int slots = HIGH-LOW + 1; // no of items in range
  
   //set the width
int w = 10;
  
   int bag[slots];
   int i = 0;
   while(i < slots) { //initializing to 0
       bag[i] = 0;
       i++;
       }
  
  
   i = 0;
   while(i <= CAPACCITY) {
       int r = (rand() % 20);
       //cout<<r<<endl;
       bag[r]++;
       i++;
   }
   i = 0;
   while(i < slots) {
       cout<<setw(w)<<i<<setw(w)<<bag[i]<<endl;
       i++;
       }
   return 0;
  
   }