How do I create a c function that takes two strings and compared them character
ID: 3933954 • Letter: H
Question
How do I create a c function that takes two strings and compared them character by character from left to right. And it returns the difference between the ascii value of the first mismatched characters, otherwise zero if both strings are equal. And printf a statement suggesting which is bigger? Without using array notation or string functions How do I create a c function that takes two strings and compared them character by character from left to right. And it returns the difference between the ascii value of the first mismatched characters, otherwise zero if both strings are equal. And printf a statement suggesting which is bigger? Without using array notation or string functionsExplanation / Answer
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include "stdio.h"
int diff(char *arr1, char *arr2){
int i, d = 0; //initialize diff as 0
for( i=0; i<*(arr1+i)!=NULL;i++){ //iterate over each element in arr1
if(*(arr1+i) != *(arr2+i)){ //if the element is different
d = ((int)*(arr1+i)) - ((int)*(arr2+i)); //get the ascii difference of two characters
return d; //return the difference
}
}
return 0; //if no difference is found, then return 0
}
int main(void) {
char *s1 = "hay", *s2 = "hai"; //initialize 2 strings
int d = diff(s1,s2); //call the diff method
if(d > 0) //print the message
printf("%s is bigger. Diff = %d",s1,d);
else if(d < 0)
printf("%s is bigger. Diff = %d",s2,d);
else
printf("Both are equal. Diff = %d",d);
return 0;
}
-----------------------------------------------
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.