c - printing common characters in three strings -
q) write c program takes input 3 strings, each of maximum 30 characters, , prints common characters present in 3 strings. each string can have different number of characters.
the code have written is:
#include<stdio.h> int main() { int c1=0 , c2=0, c3=0 ,i,x; int count1[26]={0} , count2[26]={0} , count3[26]={0}; char st1[30],st2[30],st3[30]; printf("enter string1: "); gets(st1); printf("\n enter string2: "); gets(st2); printf("\n enter string3: "); gets(st3); while(st1[c1]!='\0') { count1[st1[c1]-'a']++; c1++; } while(st2[c2]!='\0') { count2[st2[c2]-'a']++; c2++; } while(st3[c3]!='\0') { count3[st3[c3]-'a']++; c3++; } for(i=0;i<26;i++) { if(count1[i]!=0 && count2[i]!=0 && count3[i]!=0) { if (count1[i]<count2[i] && count1[i]<count3[i]) { for(x=0;x<count1;x++) { printf("\n %c ",x+'a'); } } else if(count2[i]< count1[i] && count2[i]< count3[i]) { for(x=0;x<count2;x++) { printf("%c",x+'a'); } } else { for(x=0;x<count3;x++) { printf("%c",x+'a'); } } } } } but when run code in codeblocks,continuous randomcharacters occuring continous beep beep sound till shut down system. can me this?
there various errors in code.
when print common characters, loop is:
for (x = 0; x < count1; x++) ...but
count1address of array, huge number. loop runs longer expect; accesses memory locations beyondcount[25]contain random data (at least none algorithm can make sense of) , prints it. (the beep sound comes printing character ascii code 7, alert or bell code'\a'. if on ms-dos, you'd see happy black , white faces too.)the correct loop runs number of letters stored in
count1letteri.for (x = 0; x < count1[i]; x++) ...when count letters, increase
count1[st1[c1] - 'a']++;this evoke dreaded undefined behaviour when
st1[c1] - 'a'not in range 0 25. can happen, e.g. if string"new york". either need check character lies in correct range or need extend solution full range of characters. (note assignment talks characters, not letters.)when print common characters, don't print them correctly:
printf("%c", x + 'a');here,
xrunning 0 number of occurrences of letteri. if common characters thee o's, print "abc". should printi + 'a'. (this logic error, not can crash program.)
Comments
Post a Comment