i have written c program. it's character counting program. give input below
input: abcappprc
, need output: a2b1c2p3r1
.
but gives output a2b1c2a1p3p2p1r1c1
. doing per logic have written in program. don't want count characters of string have been counted. can suggest logic should implement this?
#include <stdio.h> int main() { char str[30]= "abcappprc"; char stroutput[60]=""; char *ptr= &str, *ptr2=&str; char ch='a'; int count=0; puts(str); while (*ptr !=null) { count =0; ch = *ptr; while (*ptr2!= null) { if (*ptr2 == ch) count++; ptr2++; } printf("%c%d",*ptr, count); ptr++; ptr2 = ptr; } }
you need separate counting printing.
- the first loop goes through input , counts number of occurrences of each character, storing counts in array indexed character code.
- the second loop goes through array of counts , prints character corresponding non-zero count followed count.
for example:
#include <stdio.h> int main(void) { char str[] = "abcappprc"; int counts[256] = { 0 }; puts(str); (char *ptr = str; *ptr != '\0'; ptr++) counts[(unsigned char)*ptr]++; (int = 0; < 256; i++) { if (counts[i] != 0) printf("%c%d", i, counts[i]); } putchar('\n'); return(0); }
sample output:
abcappprc a2b1c2p3r1
i not understand first
for
loop. please explain it?
the for
control line steps through string str
1 character @ time. for
loop equivalent of outer while
loop in original code.
char *ptr = str; ... while (*ptr != '\0') { ... ptr++; }
the body of loop converts *ptr
(a plain char
) unsigned char
(so guaranteed positive), , uses value index array counts
. thus, example, on first iteration, a
mapped 65, , counts[65]
incremented. thus, each character code, loop increments count corresponding character code each time character encountered in string.
the second loop picks out non-zero counts, printing character code character followed count.
(incidentally, should have been getting compilation warning original char *ptr = &str
type mismatch between char *
, char (*)[30]
. learn when put ampersands in front of array names — seldom unless there subscript after array name. thus, &array
— not — wrong; contrast, &array[0]
valid. note on machines, null
defined ((void *)0)
, elicits warning when compare plain char
, did while (*ptr != null)
. should compare characters '\0'
in rewrite; should reserve null
use pointers.)
Comments
Post a Comment