Docsity

Strings-Computer Fundamentals-Lab Codes, Exercises of Computer Fundamentals

Toggle sidebar
bg1
// solution for last lab
#include <stdio.h>
#include <stdlib.h>
void mystery1( char *, const char * ); // prototype
int mystery3( const char *s1, const char *s2 ); // prototype
int main()
{
char *string1;
char *string2;
int x;
// if you are using pointer then you need to assign them memory
to read user input through scanf function
string1=(char*) malloc(30);
string2=(char*) malloc(30);
// if you dont do malloc then pointer is not pointing to a valid
memory address and thus can not store it and give
// segmentation fault or bus error
printf("Enter first string: ");
scanf("%s",string1);
printf("Enter first string: ");
scanf("%s",string2);
printf("Calling mystery3 \n");
x=mystery3 (string1, string2);
if(x==0)
{
printf(" String are not equal\n");
}
else if(x==1)
{
printf(" String are equal\n");
}
printf("Calling mystery1 \n");
mystery1 (string1, string2);
printf("%s\n",string1);
return 0; // indicates successful termination
} // end main
// What does this function do?
void mystery1( char *s1, const char *s2 )
{
while ( *s1 != '\0' )
++s1;
for ( ; *s1 = *s2; s1++, s2++ ); // empty statement
} // end function mystery1
int mystery3( const char *s1, const char *s2 )
docsity.com
pf2

Partial preview of the text

Download Strings-Computer Fundamentals-Lab Codes and more Exercises Computer Fundamentals in PDF only on Docsity!

// solution for last lab #include <stdio.h> #include <stdlib.h> void mystery1( char *, const char * ); // prototype int mystery3( const char *s1, const char *s2 ); // prototype

int main() { char string1; char string2; int x; // if you are using pointer then you need to assign them memory to read user input through scanf function string1=(char) malloc(30); string2=(char) malloc(30); // if you dont do malloc then pointer is not pointing to a valid memory address and thus can not store it and give // segmentation fault or bus error

printf("Enter first string: "); scanf("%s",string1); printf("Enter first string: "); scanf("%s",string2);

printf("Calling mystery3 \n"); x=mystery3 (string1, string2); if(x==0) { printf(" String are not equal\n"); } else if(x==1) { printf(" String are equal\n"); }

printf("Calling mystery1 \n"); mystery1 (string1, string2); printf("%s\n",string1);

return 0; // indicates successful termination } // end main

// What does this function do? void mystery1( char *s1, const char *s2 ) { while ( *s1 != '\0' ) ++s1;

for ( ; *s1 = *s2; s1++, s2++ ); // empty statement } // end function mystery

int mystery3( const char *s1, const char *s2 )

docsity.com

for ( ; *s1 != '\0' && *s2 != '\0'; s1++, s2++ )

if ( *s1 != *s2 ) return 0;

return 1; } // end function mystery

docsity.com