Home > Software engineering >  Why is my program returning the wrong value?
Why is my program returning the wrong value?

Time:03-27

I'm trying to write a program that takes a string as an input, and returns any characters in the string which occur more than once, along with how frequently they occur. What I haven't been able to figure out is finding a way to get the program to return "No duplicates found" for strings with no repeating characters.

# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256


char fillCharCounts (unsigned char *str, int *count) {
    int i;
    for (i = 0; * (str   i);  i  )
        count[* (str   i)]  ;
    return 0;
}

void printDups (unsigned char *str) {
    int *count = (int *) calloc (NO_OF_CHARS, sizeof (int));
    
    fillCharCounts (str, count);
    int i;
    for (i = 0; i < NO_OF_CHARS; i  )
        if (count[i] > 1)
            printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);

    /* area of concern */
    if (count[i] < 1)
        printf ("\nNo duplicates found\n");
    exit (0);

    printf ("\n");
    free (count);
}

int main() {
    unsigned char str[15] = "";
    
    printf ("Enter a word>");
    scanf ("%s", str);
    printDups (str);
    getchar();

    return 0;
}

The program returns characters that occur more than once along with their frequency, but it always returns "No duplicates found" along with this. How can i fix it so it only returns "No duplicates found" for strings with no repeating characters?

CodePudding user response:

You need to use a flag/counter say dupe_chars to track if one or more duplicate characters were found.

    int dupe_chars = 0;  // an integer flag/counter
    for (int i = 0; i < NO_OF_CHARS; i  )
        if (count[i] > 1) {
            printf ("\nLetter: %c, Occurrences: %d", i, count[i]);
              dupe_chars;  //counting duplicate letters
        }
    /* area of concern */
    if (0 != dupe_chars)
        printf ("\nDuplicates of %d chars were found\n", dupe_chars);        
    else
        printf ("\nNo duplicates were found\n");
    //exit (0);    // not necessary

  • Related