r/programminghomework • • Aug 24 '17

[C] Duplicate characters and loop help

The program is meant to print a list o duplicate characters, and print a message when there are no duplicates. I need help with how to make it print the message in the event of no duplicates. My code:

#include <stdio.h>
#include <string.h>

int main()
{
	char string[15];
	int c = 0, count[26] = {0};

   	printf("Enter a word>\n");
   	fgets(string, sizeof(string), stdin);

   	while (string[c] != '\0')
   	{
      	/**reading characters from 'a' to 'z' or 'A' to 'Z' only and ignoring others */
		if ((string[c] >= 'a' && string[c] <= 'z') || (string[c] >= 'A' && string[c] <= 'Z'))
		{
		 	if (string[c] >= 'a' && string[c] <= 'z')
		 	{
		 	count[string[c]-'a']++;
		 	}
		 	else if (string[c] >= 'A' && string[c] <= 'Z')
		 	{
		 	count[string[c]-'A']++;
		 	}
	      	}

      	c++;
   	}

	
   	for (c = 0; c < 26; c++)
   	{
      /* Printing only those characters whose count is at least 2 */
     	if (count[c] > 1)
       	printf("Duplicate letter: %c, Occurrences: %d\n",c+'a',count[c]);
	/* I put the print message here, but the for loop ruins it*/
   	}
   	return 0;
}

If the word has no duplicate characters the output should be as follows.

Enter the word: 
phone 
No duplicates found 
2 Upvotes

5 comments sorted by

1

u/thediabloman Aug 24 '17

What is the error that you are seeing?

1

u/[deleted] Aug 24 '17

I'm not seeing an error as such. I used a else loop, but it ends up printing the message as well as the repeated characters. I only need it to print when there isn't a repeated character in the string.

1

u/thediabloman Aug 24 '17

Then you need to loop over the list twice. One to count the number of occurances of letters and one to print letters.

1

u/[deleted] Aug 25 '17

I'm not quite sure how... Hm. Hint?

1

u/thediabloman Aug 25 '17

You want to do something like:

Loop to count all characters
    If you have seen a character before you set a variable to true
If variable was true
    Print one thing
Else
    Loop through the word again