Domanda

I've spent the past 5 hours trying too write this program, got halfway and realised I cant use arrays or functions, strings etc.

The problem is i need too create a program that reads integer values terminated by a sentinel value and displays a bar chart of single digit numbers(0-9). The chart shows the total number of occurrences for each number in the sequence. Here is what i have so far

EDIT: THIS IS MY REVISED CODE

#include <iostream>
using namespace std;

int main()
{
   //initilise variables
    int num = 0, count0 = 0, count1 = 0,count2 = 0,count3 = 0,count4 = 0, 
count5 =0, count6 = 0,count7 = 0,count8 = 0,count9 = 0, value;
int SENTINEL = -1;

//get numbers till a -1 values has been entered
cout << "Please enter a number: ";
while(num != SENTINEL)
{
    cin >> num;

    //adds each occurrence of number entered
    switch(num)
{
    case 0:
        count0+= 1;
        break;
    case 1:
        count1+= 1;
        break;
    case 2: 
        count2+=1;
        break;
    case 3:
        count3+= 1;
        break;
    case 4:
        count4+= 1;
        break;
    case 5: 
        count5+= 1;
        break;
    case 6:
        count6+= 1;
        break;
    case 7:
        count7+= 1;
        break;
    case 8: 
        count8+= 1;
        break;
    case 9:
        count9+= 1;
        break;
    default:;
}
}

for(int rows = 0; rows < 10; rows++)
{
    cout << endl << rows << " | ";
    for(int c = 0; c < count0; c++)
    {
        {
            cout << "*" ;

        }
    }

}

EDIT:

Im having trouble with getting the for loop for my columns too output the * on just a single row. Any idea what i should change too allow that? So far, if i input 3 zero's(count0=3) it will display 3 "*", but on all 9 rows.

È stato utile?

Soluzione 2

If you only need to count single digit numbers, then one way to go is to use 10 variables =) int count0, count1... etc... then you have almost array so, you can count input and then output counted values..

Altri suggerimenti

What you could do:

  1. Write the program with functions and arrays.
  2. Erase the functions by putting their code wherever they are called, remember to set the arguments correctly.
  3. Replace the arrays with N variables and their access with a huge switch/case:

     //arr[i] = 42;
     switch (i) {
     case 0: arr_0 = 42; break;
     case 1: arr_1 = 42; break;
     //...
     }
    

You could facilitate both by using macros, e.g. use Boost.Preprocessor to repeat the cases from 0 to N

What you should do: Say no. Tell your teacher that it's bullshit to not use the language's most basic features. But maybe wait with that until after he accepted your solution ;)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top