Question

The part that is commented 'recurring characters code' is a bit flawed as later on when I try to print the letter and number of occurrences, the letter is correct, but the number of occurrences is some random number. Can somebody explain where my logic is faulty?

#include <stdio.h>
#include <stdlib.h>
#define MAX 20

int main()
{
//declare variables
char arr[MAX], ch;
int counter1 = 0, counter2 = 0, i, j, temp, mostcommon[128], x = 0, y = 0;

//ask for user input until array reaches MAX or is interrupted by the 'X' character and append arr[i]
for(i = 0; i < MAX; i++)
{
    printf("Input %d. character into array: ", i + 1);
    ch = getchar();
    if (ch == 'X'){
    break;
    }
    getchar();
    arr[i] = ch;
    counter1++;
}

//recurring characters code
for (i = 0; i < 128; i++){
mostcommon[i] = 0;
}

x = mostcommon[0];
y = 0;

for (i = 0; i < counter1; i++)
{
    mostcommon[(int) arr[i]] += i;
}

for (i = 0; i < 128; i++){
    if (x < mostcommon[i]){
        x = mostcommon[i];
        y = i;
     }
}

//print array as it was appended
printf ("\nArray:");
for (i = 0; i < counter1; i++)
{
    printf("\narray[%d] = %c", i, arr[i]);
}

//sort array by descending ASCII value
for(i = 0; i < counter1 - 1; i++)
{
    for(j = i + 1; j < counter1; j++)
    {
        if (arr[i] < arr[j])
        {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}

//print sorted array
printf ("\n\nSorted array:");
for (i = 0; i < counter1; i++)
{
    printf("\narray[%d] = %c", i, arr[i]);
}

//print array without reoccuring characters
printf ("\n\nFinal array:");
for (i = 0; i < counter1; i++)
{
    if (arr[i] != arr[i-1]){
    printf("\narray[%d] = %c", counter2, arr[i]);
    counter2++;
    }
}

printf("\n\nThe most common character is %c and it recurred %d times", y, x);

return 0;
}
Was it helpful?

Solution

One note before: *Shouldn't you raise counter1 at the start of the loop ? Because if you don't - when X is entered it won't raise counter1 and I supposed you want number of characters entered.

Now to the code - first in the loop:

for (i = 0; i < counter1; i++)
{
    mostcommon[(int) arr[i]] += i;
}

What was your purpose? If you want the number of occurrences of the character then the loop should look like this:

for(i = 0 ; i < counter1 ; i++)
{
    mostcommon[(int)arr[i]]++;
}

as "+= i" has no purpose according to my understanding - so it would be kind of random as you describe. Hope it helped.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top