Question
#include #include bool compare(char* s1, char* s2){ // write code here for 3.2 return false; } int main () { char C[4]; char D[4]; char
#include
#include
bool compare(char* s1, char* s2){
// write code here for 3.2
return false;
}
int main ()
{
char C[4];
char D[4];
char E[4];
char* str = "hello";
char* str2 = "hello";
char* str3 = "oy";
int i;
C[0] = 'o';
C[1] = 'y';
C[2] = '!';
C[3] = '\0';
printf("C as chars: ");
for (i=0; i<4; i++) { // The usual way.
printf ("%c", C[i]);
}
printf (" ");
printf ("C as string: %s ", C); // This works if the string terminator is used.
D[0] = 'o';
D[1] = 'y';
D[2] = '!';
D[3] = '\0';
printf ("D as string: %s ", D);
E[0] = 'o';
E[1] = 'h';
E[2] = '?';
E[3] = '\0';
printf ("E as string: %s ", E);
printf ("str as string: %s ", str); // The usual way, since this is a string.
printf("str as chars: ");
for (i=0; i<5; i++) { // An alternative (unnecessarily laborious).
printf ("%c", str[i]);
}
printf (" ");
// Test equality with == (3.1)
if(C == D) {
printf("C and D are == ");
}
if(C == E) {
printf("C and E are == ");
}
if(C == str) {
printf("C and str are == ");
}
if(str == str2) {
printf("str and str2 are == ");
}
if(C == str3) {
printf("C and str3 are == ");
}
// Test equality with compare function (3.2)
if(compare(C, D) == true) {
printf("C and D are == with compare() ");
}
if(compare(C, E) == true) {
printf("C and E are == with compare() ");
}
if(compare(C, str) == true) {
printf("C and str are == with compare() ");
}
if(compare(str, str2) == true) {
printf("str and str2 are == with compare() ");
}
if(compare(C, str3) == true) {
printf("C and str3 are == with compare() ");
}
}
3.1 (a) Does the == operator correctly test for equality between strings? (b) Since arrays of chars and char* pointers act similarly, can we test equality by using a line like if(*C == *D)? Test in CodeAnywhere/Repl to verify your answers.
3.2 Make a compare.c file in your repository and complete a compare() function to evaluate whether two strings are equal. To do this, you will need to step through each string comparing characters, until you reach the string termination character. Be sure your code works for all the tested cases above, plus any others that might be important.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started