Count all characters appearing consecutively. OUTPUT: The number of characters appearing consecutively and the letters.

Can someone help me in my code? When I input Committee the output should be 3 mte and it is correct but when I input mmmmrrnzzz the output should be 4 mmrz instead I get 5 mmrz. What is wrong in my code? Can someone help me. Thanks

This is an example of what should I make.
Sample Run:
Enter string: Mississippi
3
ssp

Enter string: Committee
3
mte

Enter string: mmmmrrnzzz
4
mmrz



HERE IS MY CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<string.h>

int main (void)
{
	char string[20];
	int x, count=0;
	
				
	printf("Enter a String: ");	
	gets(string);
	
	
		for(x=1; x<=strlen(string)-1; x++)
			if (string[x] == string[x+1])
				 { 
					 count++;
				}
					 printf("%d\n", count);
	 		
	 
	 	for(x=1; x<=strlen(string)-1; x++)
	 		if (string[x] == string[x+1])
	 			{ 
				 printf("%c", string[x]);
				}
					 
 getch();
}
Last edited on
Add a cout statement showing x and x+1 before count++ and see what you get.

I think x should = 0 not 1...

It would help me read your code if you used code tags.
http://www.cplusplus.com/articles/jEywvCM9/
I don't quite understand what I should do. Should I output x and x+1? Thanks and also I already use code tags :) thank you for informing about the code tags
Last edited on
One problem is that you skip the first character - first index is 0 not 1.
1
2
3
4
5
6
for(x=1; x<=strlen(string)-1; x++)
			if (string[x] == string[x+1])
				 { 
					 count++;
				}
					 printf("%d\n", count);


You also need to skip the charater that matched the previous.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for(x=0; x <= strlen(string)-1; x++)
if (string[x] == string[x+1])
{ 
  count++;
  x++;
}
printf("%d\n", count);


for(x=0; x<=strlen(string)-1; x++)
   if (string[x] == string[x+1])
  { 
     printf("%c", string[x]);
     x++;
  }

It worked!!! Thank you very much Thomas! :)
You are very welcome.
Topic archived. No new replies allowed.