For/While Loop: Using either a for-loop or while-loop. identify how close two wo
ID: 3806521 • Letter: F
Question
For/While Loop: Using either a for-loop or while-loop. identify how close two words are by incorporating a loop using the following algorithm: First determine whether or not the two words are the same length If the words are different lengths, then output the difference of the two lengths and exit. If the words are the same length, then step through the letters of each word using a for-loop and identify the number of characters that are mismatched. For example, the words bat and bag have 1 mismatch whereas bag and bag have 0 mismatches. Output the two words and the number of mismatches.Explanation / Answer
#include<stdio.h>
void main() {
char word1[50], word2[50];
printf("Enter word 1: ");
scanf("%s", word1);
printf("Enter word 2: ");
scanf("%s", word2);
printf("Difference between word '%s' and word '%s' is %d",word1, word2, wordDiff(word1, word2));
}
int wordDiff(char *word1, char *word2) {
int length1, length2, count = 0, i;
for (length1 = 0; word1[length1]!=''; length1++); //calculate length
for (length2 = 0; word2[length2]!=''; length2++); //calculate length
if (length1 == length2){ //if lengths are equal
for (i = 0; i<length1; i++) //for every letter of both words
if (word1[i]!=word2[i]) //are equal
count ++; //increase count
return count; //and finally return count
}
if (length1 > length2) //this actullay calculate and returns the absolute value of length1 - length2
return length1 - length2;
return length2 - length1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.