write a function in c++ .... int common (string word1, string word2) which takes
ID: 3770330 • Letter: W
Question
write a function in c++ .... int common (string word1, string word2) which takes two words (let's assume the only chars in the words are all small letters ) and returns the total number of letters in common to the words. some examples:
common ("engineering", "evergreen") should return 6 (because there are 3 e's, 1 g, and 1 n and 1 r in common).
common ("aardvark", "kangaroo") should return 3 (because there are 2 a's and 1 k in common)
common ("wombat", "baboon") should return 2 (1 a and 1 b in common).
Explanation / Answer
//This program is developed in visual studio 2010
//Preprocessive directives
# include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
//Function declaration
int common(char s1[],char s2[]);
//execution starts here
int main()
{
//initialize memory to input 2 strings
char string1[100],string2[100];
int commonChar;
//enter first string details
cout<<"enter the first string ";
gets(string1);
//enter second string details
cout<<"enter the second string ";
gets(string2);
//send the 2 strings to the function and return the compared result
commonChar=common(string1,string2);
//display the final result
cout<<" The common characters in 2 strings are "<<commonChar<<endl;
getch();
}
//function definition to compare the common characters in 2 strings and return their count
int common(char s1[],char s2[])
{
//temporary variables for iteration and maintaining count
int i,j,count=0;
for(i=0; i < strlen(s1); i++) {
for(j = 0; j < strlen(s2); j++) {
//comparing each characters for equality
if(s1[i] == s2[j]) {
//increment the count,if 2 characters are same
count++;
s2[j] = '*';
break;
}
}
}
//return the final count to main function
return(count);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.