Search code examples
c++arrayshistogram

Print histogram with "*" representing relative frequencies in C++


I'm trying to convert an histogram with absolute values to an histogram showing the relative frequency of letters in a string, written by the user. The letters frequency should be represented by *. So, if the letter "A" is 1% of a string, there should be two *. 1% = two *.

When trying to calculate the frequency, the output is zero. I don't really understand why.

I've tried to search the internet, but I can't really find something that helps me. I guess I'm stuck, both in my head and coding.

This is the code for my three functions:

void berakna_histogram_abs(const string inm, int arr[ANTAL_BOKSTAVER]){

    int i, j = 0;

    while (inm[i] != '\0'){
        if (inm[i] >= 'a' && inm[i] <= 'z'){
            j = inm[i] - 'a';
            ++arr[j];
        }
        if (inm[i] >= 'A' && inm[i] <= 'Z'){
            j = inm[i] - 'A';
            ++arr[j];
        }
        i++;
    }
}
void abs_till_rel(int arr[ANTAL_BOKSTAVER], int (&ree)[ANTAL_BOKSTAVER]){

        for(int i = 0; i < ANTAL_BOKSTAVER; i++) {
            ree[i] = arr[i] / 26;
            printf("%c %lf \n", i + 'a', ree[i]);
        }

        for (int x = 0; x < ANTAL_BOKSTAVER; x++){

        }

    }

void plotta_histogram_rel(int (&ree)[ANTAL_BOKSTAVER]){

    cout << "Frekvensen av bokstäver i texten är: " << endl;
    for (int i = 0; i < ANTAL_BOKSTAVER; i++){
        cout << char(i + 'a') << " : " << ree[i] << endl;

         }
    }

I'm not allowed to do any calculations in the third function, that is only for writing the histogram. The whole program is pretty big, if you'd like, I'll provide all the code.

Any help forward is much appreciated.

Thanks!


Solution

  • void abs_till_rel(int arr[ANTAL_BOKSTAVER], int langd, double frekArr[ANTAL_BOKSTAVER]){
    //Function to calculate the relative frequency of letters in a string.
        for (int i = 0; i < ANTAL_BOKSTAVER; i++){
    
        frekArr[i] = arr[i]; //Writes over the input from the user to a new array.
    
        frekArr[i] = frekArr[i] * 200 / langd; //Calculates the relative frequency
        //*200 since 1% should be represented by two (2) *.
        }
    }
    void plotta_histogram_rel(double frekArr[ANTAL_BOKSTAVER], int langd){
    
        int j = 0;
        for (int i = 0; i < ANTAL_BOKSTAVER; i++){
        cout << char(i + 'A') << " : ";
    //Creates a histograg, horizontal, with A-Z.
    
            if(frekArr[i] > 0){
            for ( j = 0; j < frekArr[i]; j++){ 
            cout << "*";
            }
            cout << endl;
            }
    //If the index in frekArr is NOT empty, loop through the index [i] times and 
    //write double the amount of *. 
            else {
                cout << " " << endl;
    //Else, leave it empty.
            }
    }
    }
    

    I've solved the issue. See the working code above.